通过线程池进行任务处理,有时我们需要知道线程池中任务的执行状态。
通过ThreadPoolExecutor的相关API实时获取线程数量,排队任务数量,执行完成线程数量等信息。
实例
private static ExecutorService es = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(
100000
));
public static void main(String[] args) throws Exception
{
for (int i = 0; i < 100000; i++) {
es.execute(() -> {
System.out.print(1);
try{
Thread.sleep(1000);
}
catch(InterruptedException e) {
e.printStackTrace();
}
});
}
ThreadPoolExecutor tpe = ((ThreadPoolExecutor) es);
while (true) {
System.out.println();
int queueSize = tpe.getQueue().size();
System.out.println("当前排队线程数:"+ queueSize);
int acti