我们在使用线程池的时候,想知道当前线程池下创建了多少个线程,或者创建了多少个线程池数
可以通过下面的例子了解到:
-
import java.util.concurrent.ExecutorService;
-
import java.util.concurrent.Executors;
-
import java.util.concurrent.ThreadPoolExecutor;
-
/**
-
* @Description 获取线程池中的当前活动线程
-
*@Date 2019/3/13
-
*/
-
public class TestForExecutorServicePool {
-
public static void main(String[] args) {
-
ExecutorService exes = null;
-
try{
-
exes = Executors.newFixedThreadPool(10);
-
//想线程池中放入三个任务
-
exes.execute(new Task());
-
exes.execute(new Task());
-
exes.execute(new Task());
-
Thread.sleep(500);//延迟500ms,因为三个任务放入需要时间
-
//将exes转换为ThreadPoolExecutor,ThreadPoolExecutor有方法 getActiveCount()可以得到当前活动线程数
-
int threadCount = ((ThreadPoolExecutor)exes).getActiveCount();
-
System.out.println("1.threadCount===="+threadCount);
-
Thread.sleep(3000);
-
threadCount = ((ThreadPoolExecutor)exes).getActiveCount();
-
System.out.println("2.threadCount===="+threadCount);
-
exes.execute(new Task());
-
exes.execute(new Task());
-
Thread.sleep(500);
-
threadCount = ((ThreadPoolExecutor)exes).getActiveCount();
-
System.out.println("3.threadCount===="+threadCount);
-
}catch(Exception e){
-
e.printStackTrace();
-
}finally{
-
if(exec!=null){
-
exes.shutdown();
-
}
-
}
-
}
-
}
-
class Task implements Runnable{
-
@Override
-
public void run() {
-
try{
-
Thread.sleep(3000);
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
}
-
}