java threadpoolexecutor 判断线程全部结束
判断线程池中所有线程是否执行完毕
1.根据线程池中的总线程数目等于完成的线程数目
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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" ); } } |
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过