package com.product.org.admin.util;
|
|
import com.alibaba.fastjson.JSONArray;
|
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.Executors;
|
|
public class ThreadPoolTool<T> {
|
|
//单个线程处理的数据量
|
private int singleCount;
|
//处理的总数据量
|
private int listSize;
|
//开启的线程数
|
private int runSize;
|
//操作的数据集
|
private List<T> list;
|
//计数器
|
private CountDownLatch begin, end;
|
//线程池
|
private ExecutorService executorService;
|
//回调
|
private CallBack callBack;
|
|
public void setCallBack(CallBack callBack) {
|
this.callBack = callBack;
|
}
|
|
public ThreadPoolTool(int singleCount, List<T> list) {
|
this.singleCount = singleCount;
|
this.list = list;
|
if (list != null) {
|
this.listSize = list.size();
|
this.runSize = (this.listSize / this.singleCount) + 1;
|
if(singleCount==1){
|
this.runSize-=1;
|
}
|
}
|
}
|
|
public void excute(boolean async) throws InterruptedException {
|
executorService = Executors.newFixedThreadPool(runSize);
|
begin = new CountDownLatch(1);
|
end = new CountDownLatch(runSize);
|
//创建线程
|
int startIndex = 0;
|
int endIndex = 0;
|
List<T> newList = null;
|
for (int i = 0; i < runSize; i++) {
|
//计算每个线程对应的数据
|
if (i < (runSize - 1)) {
|
startIndex = i * singleCount;
|
endIndex = (i + 1) * singleCount;
|
newList = list.subList(startIndex, endIndex);
|
} else {
|
startIndex = i * singleCount;
|
endIndex = listSize;
|
newList = list.subList(startIndex, endIndex);
|
}
|
//创建线程类处理数据
|
MyThread myThread = new MyThread(newList, begin, end) {
|
@Override
|
public void method(List list) {
|
callBack.method(list);
|
}
|
};
|
//执行线程
|
if (!async) {
|
executorService.submit(myThread);
|
} else {
|
executorService.execute(myThread);
|
}
|
}
|
//计数器减一
|
begin.countDown();
|
end.await();
|
//关闭线程池
|
executorService.shutdown();
|
}
|
|
//抽象线程类
|
public abstract class MyThread<Object> implements Runnable {
|
|
private List<Object> list;
|
private CountDownLatch begin, end;
|
|
public MyThread(List<Object> list, CountDownLatch begin, CountDownLatch end) {
|
this.list = list;
|
this.begin = begin;
|
this.end = end;
|
}
|
|
@Override
|
public void run() {
|
try {
|
//执行程序
|
method(list);
|
begin.await();
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
throw new RuntimeException(e.getMessage());
|
} finally {
|
//计数器减一
|
end.countDown();
|
}
|
}
|
|
public abstract void method(List<Object> list);
|
}
|
|
//回调接口定义
|
public interface CallBack<Object> {
|
public void method(List<java.lang.Object> list);
|
}
|
|
public static void main(String[] args) {
|
JSONArray array =new JSONArray();
|
for (int i = 0; i < 5; i++) {
|
Map a=new HashMap();
|
int grade=(int)a.get("org_evel_parent");
|
while(array.size()-1!=grade){
|
array.add(new JSONArray());
|
}
|
array.getJSONArray(grade).add(a);
|
}
|
}
|
}
|