2024-08-04
版权声明:本文为博主付费文章,严禁任何形式的转载和摘抄,维权必究。 本文链接:https://www.skjava.com/mianshi/baodian/detail/5815377096

回答

在 Java 中我们可以通过如下几种方式来判断线程池中的任务是否已全部执行完成。

  • 使用 isTerminated() 方法
  • 使用 ThreadPoolExecutorgetCompletedTaskCount()
  • 使用 CountDownLatch

扩展

使用 isTerminated() 方法

isTerminated() 用来判断线程池是否结束,如果结束返回 true。使用它时我们必须要在 shutdown() 方法关闭线程池之后才能使用,否则 isTerminated() 永不为 true。

  • shutdown():拒绝接受新任务,但会继续处理已提交的任务。
  • shutdownNow():尝试停止所有正在执行的任务并返回未执行的任务列表。

如下:

public class ThreadPoolExample {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20,
                0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1024));
        
        for (int i = 0; i < 10; i++) {
            threadPoolExecutor.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " 正在执行...");
            });
        }
        
        // 关闭线程池
        threadPoolExecutor.shutdown();
        
        while(!threadPoolExecutor.isTerminated()) {
             //....
        }
    }
}