等待多线程全部完成的方法

来源:互联网 发布:需求分析师 知乎 书籍 编辑:程序博客网 时间:2024/05/17 07:47

以下两种方式是等待所有线程完成后统一调用其他方法,在while循环里面需要sleep一段小时间,要不然太耗cpu。

1、

ThreadPoolExecutor pool = new ThreadPoolExecutor(65, 65, 1,
    TimeUnit.MICROSECONDS, new ArrayBlockingQueue<Runnable>(100),  new ThreadPoolExecutor.AbortPolicy());

while (true) {
   try {
    Thread.sleep(10);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   if (pool.getActiveCount() == 0) {
    break;
   }
  }

 

2、

ExecutorService pool = Executors.newFixedThreadPool(65);

 pool.shutdown();
  while (true) {
   try {
    Thread.sleep(2);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   if (threadCount == 65) {
    break;
   }

  }

 

原创粉丝点击