实现线程池监控
线程池方法
ThreadPoolExecutor
方法名 | 作用 |
---|---|
beforeExecute | 提交线程池之前做的操作 |
afterExecute | 线程池执行之后做的操作 |
terminated | 线程池停止前做的操作 |
有可能监控的地方是在提交前跟提交后,这时可以看线程池里面的核心数据。terminated其实意义不大,因为线程池的优势不就是减少线程创建的时间吗,所以很少去shundown。
核心监控数
demo
import java.util.concurrent.*;
public class MonitorThreadPoolExecutorDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Thread.sleep(1000L);
// 方便测试
ExecutorService executor = new MonitorThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
for (int i = 0; i < 50; i++) {
Runnable runnable = () -> {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
executor.execute(runnable);
}
executor.shutdown();
System.out.println("Thread Main End!");
}
}
class MonitorThreadPoolExecutor extends ThreadPoolExecutor {
public MonitorThreadPoolExecutor(int arg0, int arg1, long arg2, TimeUnit arg3, BlockingQueue<Runnable> arg4) {
super(arg0, arg1, arg2, arg3, arg4);
}
@Override
protected void beforeExecute(Thread paramThread, Runnable paramRunnable) {
System.out.println("work_task before:" + paramThread.getName());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
System.out.println("work_task after worker thread is :" + r);
System.out.println("terminated getCorePoolSize:" + this.getCorePoolSize() + ";getPoolSize:" + this.getPoolSize() + ";getTaskCount:" + this.getTaskCount() + ";getCompletedTaskCount:"
+ this.getCompletedTaskCount() + ";getLargestPoolSize:" + this.getLargestPoolSize() + ";getActiveCount:" + this.getActiveCount());
}
@Override
protected void terminated() {
/*System.out.println("terminated getCorePoolSize:" + this.getCorePoolSize() + ";getPoolSize:" + this.getPoolSize() + ";getTaskCount:" + this.getTaskCount() + ";getCompletedTaskCount:"
+ this.getCompletedTaskCount() + ";getLargestPoolSize:" + this.getLargestPoolSize() + ";getActiveCount:" + this.getActiveCount());
System.out.println("ThreadPoolExecutor terminated:");*/
}
}
或者
线程池动态修改参数
我们可以通过分布式配置中心进行调整线程池大小。注意:核心线程数>=最大线程池数