新手怎么做网站打理/外贸出口平台网站
2021版Java线程池教程18:如何监控线程池?介绍 getActiveCount、getPoolSize、getLargestPoolSize、getTaskCount、getCompletedTaskCount、getQueue、beforeExecutor、afterExecutor、terminated 方法的作用及用法。
2021版Java线程池教程18:如何监控线程池?
视频全集
-
2021版Java线程池教程
-
2021版Java多线程教程
代码
- Github地址【全部代码】
MonitorThreadPool.class
package main;import java.util.concurrent.*;public class MonitorThreadPool extends ThreadPoolExecutor {public MonitorThreadPool(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue) {super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);}/*** 每次执行任务前调用*/@Overrideprotected void beforeExecute(Thread t, Runnable r) {monitor();}/*** 每次任务完成后调用*/@Overrideprotected void afterExecute(Runnable r, Throwable t) {monitor();}/*** 线程池关闭前调用*/@Overrideprotected void terminated() {monitor();}/*** 监控线程池情况*/public void monitor() {System.out.print("正在工作的线程数:" + getActiveCount() + "\t");System.out.print("当前存在的线程数:" + getPoolSize() + "\t");System.out.print("历史最大的线程数:" + getLargestPoolSize() + "\t");System.out.print("已提交的任务数:" + getTaskCount() + "\t");System.out.print("已完成的任务数:" + getCompletedTaskCount() + "\t");System.out.println("队列中的任务数:" + getQueue().size());}
}
Task.class
package main;public class Task implements Runnable {/*** 执行时间*/private int timeout;public Task(int timeout) {this.timeout = timeout;}@Overridepublic void run() {try {// 使当前线程休眠指定时间Thread.sleep(timeout * 1000L);} catch (InterruptedException e) {e.printStackTrace();}}
}
Main.class
package main;import java.util.concurrent.*;/*** @author 【B站】人人都是程序员* @author 【掘金】人人都是程序员* @author 【CSDN】人人都是程序员* @author 【今日头条】人人都是程序员* @author 【官方网站】www.gorhaf.com* @author 【微信公众号】gorhaf* 欢迎大家扫描下方二维码关注我们* █▀▀▀▀▀▀▀██▀██████▀▀▀▀██▀▀▀▀▀▀▀█* █ █▀▀▀█ █▄ ▀ ▄▄█▄█▄█▀██ █▀▀▀█ █* █ █ █ █▄▄▀▄▀█▄▄ ██▀ █ █ █ █* █ ▀▀▀▀▀ █ █ █▀▄▀▄ █ █ █ ▀▀▀▀▀ █* █▀▀▀▀▀█▀▀▀▀▀█ █▀▄▀▀█ ▄▀█▀█▀█▀██* █▄▄▄ ██▀█ █▀▀ ▀ ▄ ▄▀▄ ███▄█* ██ ▀▀█▀ ▄ ▄ █▀▄▄▄▀▄▀▄ ▄██▀▀▄██* █ █▄▄ ▀ █ ▄█▄▄▄▀▄▀█▄ ▄ ▄ █ █▄█* █ ▄██▄▀██▄ █ ▀▄▀ ▀▀ ▄▄▄▀██▀▄██* █ █▀▀█▀▀█▀ █▀▀█▄▀▀█▀▄ ▀▄ █▄█* █ █▀▀██▀▀█▀ █▀▀ ██▄▀▀▀▀▀█▀ ▀█* █▀▀▀▀▀▀▀█ ▄██▄▄▀▀▀▄▄▀ █▀█ ▄▄█* █ █▀▀▀█ █▀ ▄█ █▀ ▄▀▄▄ ▀▀▀ ▀▀ █* █ █ █ █ ▄▀▀▀█▄ ▄▀▄▀ █▀▀▀ ▀ ▄█* █ ▀▀▀▀▀ █ ▀█ ▀█▄ █▄█▄▄█ ▄▀▄██* ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀*/
public class Main {public static void main(String[] args) {// 创建带监控的线程池MonitorThreadPool threadPool = new MonitorThreadPool(1, 3, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2));try {// 提交多个任务for (int i = 5; i > 0; i--) {// 创建任务Task task = new Task(i);// 提交任务threadPool.submit(task);// 每隔500毫秒提交一个Thread.sleep(500);}// 使主线程休眠6秒钟Thread.sleep(6000);// 关闭线程池之前获取一次情况threadPool.monitor();} catch (InterruptedException e) {e.printStackTrace();} finally {// 关闭线程池threadPool.shutdown();}}
}