优化3:实现告警功能
创建DtpMonitor监控类
```package com.laoyang.dtp;
import org.springframework.beans.factory.InitializingBean;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
- @author:Kevin
- @create: 2023-10-25 11:05
- @Description: 优化之监听器:
- 监听活跃的线程数
- 开始定时任务
*/
public class DtpMonitor implements InitializingBean {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
@Override
public void afterPropertiesSet() throws Exception {
//每隔5秒执行一次这个方法
executor.scheduleAtFixedRate(() -> {
for (Map.Entry<String, DtpExecutor> entry : DtpUtil.map.entrySet()) {
String name = entry.getKey();
DtpExecutor exectuor = entry.getValue();
//线程池的活跃数量
int activeCount = exectuor.getActiveCount();
if (activeCount > 20){
//TODO 线程池活跃线程池告警
System.out.println("告警!");
}
}
},5,5, TimeUnit.SECONDS);
}
}
```