package com.rc.openapi.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadUtils {
// 单个线程处理的数据量
private int singleCount;
// 处理的总数据量
private int listSize;
// 开启的线程数
private int runSize;
// 操做的数据集
private List<HashMap<Object, Object>> list;
// 计数器
private CountDownLatch begin, end;
// 线程池
private ExecutorService executorService;
// 回调
private CallBack callBack;
public void setCallBack(CallBack callBack) {
this.callBack = callBack;
}
public ThreadUtils(int singleCount, List<HashMap<Object, Object>> list) {
this.singleCount = singleCount;
this.list = list;
if (list != null) {
this.listSize = list.size();
this.runSize = (this.listSize / this.singleCount) + 1;
}
}
public void excute() throws InterruptedException {
executorService = Executors.newFixedThreadPool(runSize);
begin = new CountDownLatch(1);
end = new CountDownLatch(runSize);
//建立线程
int startIndex = 0;
int endIndex = 0;
List<HashMap<Object, Object>> 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<HashMap<Object, Object>> myThread = new MyThread(newList, begin, end) {
@Override
public void method(List list) {
callBack.method(list);
}
};
//执行线程
executorService.execute(myThread);
}
//计数器减一
begin.countDown();
end.await();
//关闭线程池
executorService.shutdown();
}
//抽象线程类
public abstract class MyThread<T> implements Runnable {
private List<T> list;
private CountDownLatch begin, end;
public MyThread(List<T> 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();
} finally {
//计数器减一
end.countDown();
}
}
public abstract void method(List<T> list);
}
// 回调接口定义
public interface CallBack<T> {
void method(List<T> list);
}
public static void main(String[] agrs) {
List<HashMap<Object, Object>> list = new ArrayList<>();
for (int i = 0; i < 985; i++) {
HashMap<Object, Object> map = new HashMap<>();
map.put("A" + i, "00" + i);
list.add(map);
}
System.out.println(list.toString());
ThreadUtils tool = new ThreadUtils(5, list);
tool.setCallBack(new CallBack<HashMap<Object, Object>>() {
@Override
public void method(List<HashMap<Object, Object>> list) {
for (HashMap<Object, Object> objectObjectHashMap : list) {
try {
Thread.sleep(10000);
System.out.print(Thread.currentThread().getId() + ":" + objectObjectHashMap + " ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
});
try {
tool.excute();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}