线程池监控

实现线程池监控

线程池方法

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:");*/
    }

}

或者

在这里插入图片描述

线程池动态修改参数

在这里插入图片描述
我们可以通过分布式配置中心进行调整线程池大小。注意:核心线程数>=最大线程池数

参考博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值