参考:https://blog.csdn.net/l18848956739/article/details/89363321

但在实际开发过程中,在线程池使用过程中可能会遇到各方面的故障,如线程池阻塞,无法提交新任务等。

如果你想监控某一个线程池的执行状态,线程池执行类 ThreadPoolExecutor 也给出了相关的 API, 能实时获取线程池的当前活动线程数、正在排队中的线程数、已经执行完成的线程数、总线程数等。

总线程数 = 排队线程数 + 活动线程数 + 执行完成的线程数。

线程池使用示例:

 

private static ExecutorService es = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(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 activeCount = tpe.getActiveCount();
        System.out.println("当前活动线程数:" + activeCount);
 
        long completedTaskCount = tpe.getCompletedTaskCount();
        System.out.println("执行完成线程数:" + completedTaskCount);
 
        long taskCount = tpe.getTaskCount();
        System.out.println("总线程数:" + taskCount);
 
        Thread.sleep(3000);
    }
 
}

 

posted on 2019-08-15 16:58  lshan  阅读(3426)  评论(0编辑  收藏  举报