简单总结两种实现方式:
一、应用 Callable();二、利用计数器
egg:
一、应用 Callable()
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(6);
List<FutureTask<Object>> futureTasks = new ArrayList<FutureTask<Object>>();
futureTasks.add(new FutureTask<>(new Callable<Object>() {
@Override
public String call() {
// 线程1执行程序
return "线程1返回结果";
}
}));
futureTasks.add(new FutureTask<>(new Callable<Object>() {
@Override
public String call() {
// 线程2执行程序
return "线程2返回结果";
}
}));
// 加入 线程池
for (FutureTask<Object> futureTask : futureTasks) {
executorService.submit(futureTask);
}
// 获取线程返回结果
for (int i = 0; i < futureTasks.size(); i++) {
try {
String flag = (String) futureTasks.get(i).get();
log.info(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
// 执行后续程序
二、利用计数器
// 创建线程
public class RetailerResultAllocationThread implements Runnable {
private List<RetailerCalculationResultAllocationVo> resultAllocationVos;
private CountDownLatch latch;
public RetailerResultAllocationThread(List<RetailerCalculationResultAllocationVo> resultAllocationVos, CountDownLatch latch){
this.resultAllocationVos = resultAllocationVos;
this.latch = latch;
}
@Override
public void run() {
// ... 线程执行程序
// 计数器计数
latch.countDown();
}
}
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
try {
List<List<RetailerCalculationResultAllocationVo>> list = new ArrayList<>();
// 创建计数器
CountDownLatch latch = new CountDownLatch(list.size());
for (List<RetailerCalculationResultAllocationVo> resultAllocationVos : list) {
executorService.submit(new RetailerResultAllocationThread(resultAllocationVos, latch));
}
// 等待 更新线程更新完再落地数据
latch.await();
} catch (InterruptedException e) {
log.error(e.getMessage());
}finally {
if(executorService != null && !executorService.isShutdown()){
executorService.shutdown();
}
}
log.info("线程执行完毕!");
// 执行后续程序