一种优化操作list、数组的多线程解决方案。
这几天接触到了一些操作list的功能,由于list太长,加上每条数据的处理时间,导致性能下降,正好利用学来的多线程知识和网上的资料结合实践一番,写出了一个通用类如下。
/**
* 操作数组的线程
*
* @author 80004133
*/
public abstract class OperateListThread{
/**
* 核心数组,用户需要操作的数组
*/
public Object[] arr;
private static final Logger logger = LoggerFactory.getLogger(OperateListThread.class);
/**
* 操作数组线程的数量,默认为5
*/
private int threadNum = 5;
ExecutorService exec;
public OperateListThread(List obj, int threadNum){
this.arr = obj.toArray();
this.threadNum = threadNum;
exec = Executors.newFixedThreadPool(threadNum+1);
}
/**
* 获取操作数组后的结果
* <p>
* 有返回结果时重写该方法
* </p>
* @return
*/
public Object getResult(){
return null;
};
/**
* 用户需要实现的方法
* <p>
* 代表用户希望做什么事情,该方法被run方法调用,需要用户实现
* </p>
*/
public abstract void doRun(int index);
/**
* 调用此方法开始工作
* @throws InterruptedException
*/
public void doWork() throws InterruptedException {
logger.info("Work start ------");
long start = System.currentTimeMillis();
int length = arr.length;
CountDownLatch latch = new CountDownLatch(arr.length % threadNum == 0 ? threadNum : threadNum+1);
logger.info("length:" + length + ":" + "latch:" + latch.getCount());
for (int j = 0; j < length; j += length / threadNum) {
MyThread m = null;
if ((j + (length / threadNum)) <= length) {
m = new MyThread(arr, j, j + length / threadNum, latch);
} else {
m = new MyThread(arr, j, length, latch);
}
exec.execute(m);
}
latch.await();
exec.shutdown();
logger.info("Spand time:" + (System.currentTimeMillis() - start));
logger.info("Work end -------");
}
public class MyThread implements Runnable {
Object[] arr;
int startIndex;
int endIndex;
CountDownLatch latch;
public MyThread(Object[] arr, int startIndex, int endIndex, CountDownLatch latch) {
this.arr = arr;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.latch = latch;
}
@Override
public void run() {
for (int i = startIndex; i < endIndex; i++) {
//要做的事
doRun(i);
}
logger.info(Thread.currentThread().getName());
latch.countDown();
}
}
public static void main(String[] args) throws InterruptedException{
List<Integer> arr = new ArrayList<>();
for (int i = 1; i <= 10000; i++) {
arr.add(i);
}
// int sum = 0;
// for (int a: arr) {
// sum += a;
// }
// System.out.println(sum);
OperateListThread op = new OperateListThread(arr, 5) {
public int sum = 0;
public Object getResult() {
return sum;
}
@Override
public void doRun(int index) {
sum += (int) arr[index];
}
};
op.doWork();
int result = (int)op.getResult();
System.out.println(result);
}
}
main方法举了一个很简单的使用实例,计算1+2+3+...+10000的和。这个通用类是一个抽象类,用法是实现这个抽象类,并只需要实现简单的doRun()方法,这个方法主要是对list做什么样的操作,index代表当前数组的位置,核心数组为arr。若你需要得到返回值,可以重写getResult()方法来获取返回值。
当然,有更好的方案或可以改正的地方欢迎联系我(QQ:2470244153),或在评论处留下您的留言。
一种优化操作list、数组的多线程解决方案。的更多相关文章
- [转]通俗易懂的php多线程解决方案
原文: https://www.w3cschool.cn/php/php-thread.html --------------------------------------------------- ...
- 绝对好文C#调用C++DLL传递结构体数组的终极解决方案
C#调用C++DLL传递结构体数组的终极解决方案 时间 2013-09-17 18:40:56 CSDN博客相似文章 (0) 原文 http://blog.csdn.net/xxdddail/art ...
- JS中几种常见的数组算法(前端面试必看)
JS中几种常见的数组算法 1.将稀疏数组变成不稀疏数组 /** * 稀疏数组 变为 不稀疏数组 * @params array arr 稀疏数组 * @return array 不稀疏的数组 */ f ...
- 一种使用pyinstaller时图标问题解决方案
一种使用pyinstaller时图标问题解决方案 0x00 场景 使用pyinstaller将.py文件编译成.exe文件时,想要使用自己心仪的图标(.ico)比较麻烦.在使用pyinstalle ...
- Numpy的ndarry:一种多维数组对象
Numpy的ndarry:一种多维数组对象 Numpy最重要的一个特点就是其N维数组对象(即ndarry),该对象是一个快速而灵活的大数据集容器.你可以利用这种数组对整块数据执行一些数学运算,其语法跟 ...
- Java并发和多线程2:3种方式实现数组求和
本篇演示3个数组求和的例子. 例子1:单线程例子2:多线程,同步求和(如果没有计算完成,会阻塞)例子3:多线程,异步求和(先累加已经完成的计算结果) 例子1-代码 package cn.fansuni ...
- lua多线程解决方案
直观的讲:lua并不支持多线程,lua语言本身具有携程功能,但携程仅仅是一种中继器. lua多线程的目的:有并发需求时,共享一些数据. 例如使用lua写一个并发服务器.用户登陆之后,用户数据储存在lu ...
- 几种php 删除数组元素方法
几种php教程 删除数组元素方法在很多情况下我们的数组会出现重复情况,那我们删除数组中一些重复的内容怎么办,这些元素我必须保持他唯一,所以就想办法来删除它们,下面利用了遍历查询来删除重复数组元素的几种 ...
- 堆的 两种实现 (数组和STL)
基本思想: 两种操作都跟树的深度成正比,所以复杂度 O(log(n)) ; push():在向堆中插入数值时,首先在堆的末尾插入该数值,然后不断向上提直到没有大小颠倒为止. pop(): 从堆中取出 ...
随机推荐
- SpringBoot的学习二:整合Redis,JPA,Mybatis
Redis介绍: 是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API 特性: Redis 与其他 key - value 缓 ...
- odoo10学习笔记二:继承(扩展)、模块数据
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/11189252.html 一:继承 在不改变底层对象的时候添加新的功能——这是通过继承机制来实现的,作为在现有 ...
- LearnOpenGL.PBR.理论
判断一种PBR光照模型是否是基于物理的,必须满足以下三个条件: ()基于微平面(Microfacet)的表面模型.Be based on the microfacet surface model. ( ...
- 机器学习(4)——PCA与梯度上升法
主成分分析(Principal Component Analysis) 一个非监督的机器学习算法 主要用于数据的降维 通过降维,可以发现更便于人类理解的特征 其他应用:可视化.去噪 通过映射,我们可以 ...
- 5.3 RDD编程---数据读写
一.文件数据读写 1.本地文件系统的数据读写 可以采用多种方式创建Pair RDD,其中一种主要方式是使用map()函数来实现 惰性机制,即使输入了错误的语句spark-shell也不会马上报错. ( ...
- IP、MAC和端口号(六)
在茫茫的互联网海洋中,要找到一台计算机非常不容易,有三个要素必须具备,它们分别是 IP 地址.MAC 地址和端口号. 一.IP地址 IP地址是 Internet Protocol Address 的缩 ...
- Access-Control-Allow-Origin 响应一个携带身份信息(Credential)的HTTP请求时,必需指定具体的域,不能用通配符
https://www.cnblogs.com/raind/p/10771778.html Access-Control-Allow-Origin.HTTP响应头,指定服务器端允许进行跨域资源访问的来 ...
- zzDeep Learning Papers Translation(CV)
Deep Learning Papers Translation(CV) Image Classification AlexNetImageNet Classification with Deep C ...
- Java链接Oracle
首先在Navicat里面链接Oracle: 连接时老报错:ORA-12505, TNS:listener does not currently know of SID given in connect ...
- 高效Redis工具类
一.引言 本篇博客以redis缓存为主.至于什么是redis缓存?还有没有其它的缓存?哪个缓存的性能会更好?这里就不一一做介绍了!(有兴趣的可以自己去百度一下) 在日常的开发中,我们或多或少(必须)的 ...