主线程等待线程池里所有线程执行完成之后再执行
- 使用CountDownLatch来实现
public class TestThread {
private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 100,
60L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new ThreadFactoryBuilder().setNameFormat("job-task-%d").build());
public static void execute(Runnable runnable) {
threadPool.execute(runnable);
}
public static void shutDown() {
threadPool.shutdown();
}
public static void main(String[] args) {
List list = new ArrayList<String>();
list.add("a");list.add("b");list.add("c");list.add("d");list.add("e");list.add("f");
final CountDownLatch latch = new CountDownLatch(list.size());
System.out.println("kaishile !");
list.stream().forEach(x->{
TestThread.execute(()-> test((String) x,latch));
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=====主线程执行完成了!");
TestThread.shutDown();
System.out.println("=====线程池关闭了!");
}
public static void test(String a,CountDownLatch latch){
System.out.println(a);
latch.countDown();
}
}
===========================================
打印内容如下:
kaishile !
a
b
c
d
e
f
=====主线程执行完成了!
=====线程池关闭了!
Process finished with exit code 0
版权声明:本文为weixin_43525585原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。