如何判断线程池中所有线程是否执行完毕

1.判断线程池中所有线程是否执行完毕

  • 根据线程池中的总线程数目等于完成的线程数目

  
  
  1. package com.luna.thread;
  2. import java.util.Random;
  3. import java.util.concurrent.LinkedBlockingQueue;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. import java.util.concurrent.TimeUnit;
  6. public class ThreadsIsDone {
  7. public static void main(String[] args) {
  8. // 创建一个10个线程的线程池
  9. ThreadPoolExecutor pool = new ThreadPoolExecutor( 10, 10, 0L, TimeUnit.MILLISECONDS,
  10. new LinkedBlockingQueue<Runnable>());
  11. for ( int i = 0; i < 10; i++) {
  12. pool.submit( new Runnable() {
  13. public void run() {
  14. System.out.println(
  15.                  "当前线程:" + Thread.currentThread().getName() + ",打印随机数:" + new Random().nextInt( 1000));
  16. }
  17. });
  18. }
  19. System.out.println( "pool.getTaskCount():" + pool.getTaskCount());
  20. System.out.println( "pool.getCompletedTaskCount():" + pool.getCompletedTaskCount());
  21. //当线程池完成的线程数等于线程池中的总线程数
  22. boolean allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();
  23. System.out.println(allThreadsIsDone);
  24. if (allThreadsIsDone) {
  25. System.out.println( "全部执行完成");
  26. }
  27. while (!allThreadsIsDone) {
  28. allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();
  29. if (allThreadsIsDone) {
  30. System.out.println( "全部执行完成");
  31. }
  32. }
  33. }
  34. }
  • 当调用ExecutorService的shutdown()和awaitTermination()

  
  
  1. package com.luna.thread;
  2. import java.util.Random;
  3. import java.util.concurrent.LinkedBlockingQueue;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. import java.util.concurrent.TimeUnit;
  6. public class ThreadDone {
  7. public static void main(String[] args) {
  8. // 创建一个10个线程的线程池
  9. ThreadPoolExecutor pool = new ThreadPoolExecutor( 10, 10, 0L, TimeUnit.MILLISECONDS,
  10. new LinkedBlockingQueue<Runnable>());
  11. for ( int i = 0; i < 10; i++) {
  12. pool.submit( new Runnable() {
  13. public void run() {
  14. System.out.println(
  15. "当前线程:" + Thread.currentThread().getName() + ",打印随机数:" + new Random().nextInt( 1000));
  16. }
  17. });
  18. }
  19. pool.shutdown();
  20. try {
  21. pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. System.out.println( "all thread complete");
  26. }
  27. }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值