1.自定义可监控线程池
@Bean("xyThreadPoolTaskExecutor")
public ThreadPoolExecutor threadPoolExecutor() {
return new ThreadPoolExecutor(20, 30, 10, TimeUnit.MINUTES, new ArrayBlockingQueue(10), new AbortPolicy()) {
@Override
protected void beforeExecute(Thread t, Runnable r) {
int poolSize = this.getPoolSize();
System.out.println("poolSize-->" + poolSize);
// TODO 监控内容
super.beforeExecute(t, r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
// TODO 监控内容
super.afterExecute(r, t);
}
};
}
2.开启异步功能
@EnableAsync
3.使用线程池异步执行
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {
@Override
@Async("xyThreadPoolTaskExecutor")
public void test(String name) {
String message = MessageFormat.format("threadId-:{0},threadName-:{1},call:{2}", Thread.currentThread().getId(), Thread.currentThread().getName(), name);
log.info("3333333...start.." + message);
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("3333333...end.." + message);
}
}