有些时候,我们会使用线程池去加速某些耗时操作,常常使用到定长线程池 FixedThreadPool。主线程如何等待子线程结束,再继续执行。
1. 定长线程池声明。声明10个线程组成的池子
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
2.编写自己的线程 thread。可以实现 Runnable接口,参数自己定义,可以将需要返回的值以参数的形式传递进来。
import java.util.List;
import java.util.Map;
public class FixedExcutorThread implements Runnable {
//...
@Override
public void run() {
// do something
}
}
也可以实现Callable接口,定义好需要返回的类型
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
public class SingleExcutorThread implements Callable<Map<Integer, TbBean>> {
private WarehouseMapper mapper;
SingleExcutorThread(WarehouseMapper mapper){
this.mapper = mapper;
}
@Override
public Map<Integer, TbBean> call(){
List<TbBean> storageTbBeanList = mapper.selectWarehousesFromStorageTb();
return storageTbBeanList.stream()
.collect(Collectors.toMap(TbBean::getId, a -> a, (k1, k2) -> k1));
}
}
3. 调用方式
// Runnable
FixedExcutorThread thread = new FixedExcutorThread(...); // 自行修改参数
fixedThreadPool.execute(thread);
// Callable
SingleExcutorThread calledThread = new SingleExcutorThread(...);
Future<Map<Integer, DmStorageTbBean>> future = fixedThreadPool.execute(calledThread);
xxx = future.get(); // get获取call()返回结果。它是阻塞方法
fixedThreadPool.shutdown(); // 关闭,子线程不结束线程池不会关闭
4.如果主线程需等待子线程结束再做其他事。由下面代码进行判断
fixedThreadPool.awaitTermination(60, TimeUnit.MINUTES); // 等待子线程最长时间 1 个小时
if (fixedThreadPool.isTerminated()) {
//...
}
参考文献
https://blog.youkuaiyun.com/u011974987/article/details/51027795
https://www.jianshu.com/p/7afa3c663863