主线程等待线程池里所有线程执行完成之后再执行

主线程等待线程池里所有线程执行完成之后再执行

  1. 使用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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值