判断线程池中所有线程是否执行完毕
1.根据线程池中的总线程数目等于完成的线程数目
package com.luna.thread; import java.util.Random; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadsIsDone { public static void main(String[] args) { // 创建一个10个线程的线程池 ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); for (int i = 0; i < 10; i++) { pool.submit(new Runnable() { public void run() { System.out.println( "当前线程:" + Thread.currentThread().getName() + ",打印随机数:" + new Random().nextInt(1000)); } }); } System.out.println("pool.getTaskCount():" + pool.getTaskCount()); System.out.println("pool.getCompletedTaskCount():" + pool.getCompletedTaskCount()); //当线程池完成的线程数等于线程池中的总线程数 boolean allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount(); System.out.println(allThreadsIsDone); if (allThreadsIsDone) { System.out.println("全部执行完成"); } while (!allThreadsIsDone) { allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount(); if (allThreadsIsDone) { System.out.println("全部执行完成"); } } } }
2.当调用ExecutorService的shutdown()和awaitTermination()
package com.luna.thread; import java.util.Random; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadDone { public static void main(String[] args) { // 创建一个10个线程的线程池 ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); for (int i = 0; i < 10; i++) { pool.submit(new Runnable() { public void run() { System.out.println( "当前线程:" + Thread.currentThread().getName() + ",打印随机数:" + new Random().nextInt(1000)); } }); } pool.shutdown(); try { pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("all thread complete"); } }