java线程池获取 当前线程池活动的线程数(线程池数)

博客主要围绕线程池展开,介绍了在使用线程池时,若想了解当前线程池创建的线程数量以及线程池数量,可通过给出的例子来知晓。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

我们在使用线程池的时候,想知道当前线程池下创建了多少个线程,或者创建了多少个线程池数

可以通过下面的例子了解到:


 
  1. import java.util.concurrent.ExecutorService;

  2. import java.util.concurrent.Executors;

  3. import java.util.concurrent.ThreadPoolExecutor;

  4.  
  5. /**

  6. * @Description 获取线程池中的当前活动线程

  7. *@Date 2019/3/13

  8. */

  9. public class TestForExecutorServicePool {

  10. public static void main(String[] args) {

  11.  
  12. ExecutorService exes = null;

  13. try{

  14.  
  15. exes = Executors.newFixedThreadPool(10);

  16.  
  17. //想线程池中放入三个任务

  18. exes.execute(new Task());

  19. exes.execute(new Task());

  20. exes.execute(new Task());

  21. Thread.sleep(500);//延迟500ms,因为三个任务放入需要时间

  22. //将exes转换为ThreadPoolExecutor,ThreadPoolExecutor有方法 getActiveCount()可以得到当前活动线程数

  23. int threadCount = ((ThreadPoolExecutor)exes).getActiveCount();

  24. System.out.println("1.threadCount===="+threadCount);

  25. Thread.sleep(3000);

  26.  
  27. threadCount = ((ThreadPoolExecutor)exes).getActiveCount();

  28. System.out.println("2.threadCount===="+threadCount);

  29.  
  30. exes.execute(new Task());

  31. exes.execute(new Task());

  32. Thread.sleep(500);

  33.  
  34. threadCount = ((ThreadPoolExecutor)exes).getActiveCount();

  35. System.out.println("3.threadCount===="+threadCount);

  36.  
  37. }catch(Exception e){

  38. e.printStackTrace();

  39. }finally{

  40. if(exec!=null){

  41. exes.shutdown();

  42. }

  43. }

  44. }

  45.  
  46. }

  47. class Task implements Runnable{

  48. @Override

  49. public void run() {

  50. try{

  51. Thread.sleep(3000);

  52. }catch(Exception e){

  53. e.printStackTrace();

  54. }

  55. }

  56. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wx: fulltilt8

文章原创,对你有用的话请打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值