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

 

 

 

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

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

 
  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. }


版权声明:本文为u014191624原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。