监控的属性
- taskCount : 线程池需要执行的任务数量
- completedTaskCount: 线程池在运行过程中已完成的任务数量
- largestPoolSize : 线程池里曾经创建过的最大线程数量
- getPoolSize : 线程池的线程数量
- getActiveCount : 获取活动的线程数
监控示例
监控方法
- public long getTaskCount() //线程池已执行与未执行的任务总数
- public long getCompletedTaskCount() //已完成的任务数
- public int getPoolSize() //线程池当前的线程数
- public int getActiveCount() //线程池中正在执行任务的线程数量
示例代码如下:
public class MonitorThreadPoolUtil implements Runnable
{
private ThreadPoolExecutor executor;
private int seconds;
private boolean run=true;
public MonitorThreadPoolUtil(ThreadPoolExecutor executor, int delay)
{
this.executor = executor;
this.seconds=delay;
}
public void shutdown(){
this.run=false;
}
@Override
public void run()
{
while(run){
System.out.println(
String.format("[monitor] 池大小:%d,核心数:%d, 活跃数: %d, 完成数: %d, 任务数: %d, 线程结束没: %s, 任务结束没: %s",
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}