线程池是我们平时开发中使用较多的一种组件,其主要监控点在于池中的线程和阻塞队列中的任务情况。
构建一个线程池
先构建一个基本的线程池,并看看有哪些参数我们可以直接获取到
public class ThreadPoolMonitor {
private final static Logger log = LoggerFactory.getLogger(ThreadPoolMonitor.class);
private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 0,
TimeUnit.SECONDS, new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("my_thread_pool_%d").build());
public static void main(String[] args) {
log.info("Pool Size: " + threadPool.getPoolSize());
log.info("Active Thread Count: " + threadPool.getActiveCount());
log.info("Task Queue Size: " + threadPool.getQueue().size());
log.info("Completed Task Count: " + threadPool.getCompletedTaskCount());
}
}
[main] INFO thread.ThreadPoolMonitor - Pool Size: 0
[main] INFO thread.ThreadPoolMonitor - Active Thread Count: 0
[main] INFO thread.ThreadPoolMonitor - Task Queue Size: 0
[main] INFO thread.ThreadPoolMonitor - Completed Task Count: 0
[main] INFO thread.ThreadPoolMonitor - Completed Task Count: 0
定时监控
加上定时一秒一次的任务来监控,线程池的使用情况
public class ThreadPoolMonitor {
private final static Logger log = LoggerFactory.getLogger(ThreadPoolMonitor.class);
private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 0,
TimeUnit.SECONDS, new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("my_thread_pool_%d").build(), new ThreadPoolExecutor.DiscardOldestPolicy());
public static void main(String[] args) {
// 每秒输出一次线程池的使用情况
printThreadPoolState();
// 模拟任务执行
IntStream.rangeClosed(0, 20).forEach(i -> {
// 每100毫秒,执行一个任务
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 每个处理一个任务耗时5秒
threadPool.submit(() -> {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
});
}
private static void printThreadPoolState() {
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
log.info("Pool Size: " + threadPool.getPoolSize());
log.info("Active Thread Count: " + threadPool.getActiveCount());
log.info("Task Queue Size: " + threadPool.getQueue().size());
log.info("Completed Task Count: " + threadPool.getCompletedTaskCount());
log.info("---------------");
}, 0, 1, TimeUnit.SECONDS);
}
}