Java多线程(ExecutorService), 等待所有线程执行完毕.

常用的两种方式:

第一种方式:来自大神cletus的回答, 原文链接

  1.  
    ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
  2.  
    while(...) {
  3.  
    taskExecutor.execute(new MyTask());
  4.  
    }
  5.  
    taskExecutor.shutdown();
  6.  
    try {
  7.  
    taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
  8.  
    } catch (InterruptedException e) {
  9.  
    ...
  10.  
    }

第二种方式:来自大神ChssPly76的回答, 原文链接

  1.  
    CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
  2.  
    ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
  3.  
    while(...) {
  4.  
    taskExecutor.execute(new MyTask());
  5.  
    }
  6.  
     
  7.  
    try {
  8.  
    latch.await();
  9.  
    } catch (InterruptedException E) {
  10.  
    // handle
  11.  
    }

然后在线程方法中加入:

  1.  
    try {
  2.  
    ...
  3.  
    } catch (Exception e) {
  4.  
    e.printStackTrace();
  5.  
    }finally {
  6.  
    countDownLatch.countDown();
  7.  
    }
原文地址:https://www.cnblogs.com/telwanggs/p/13979612.html