- 项目中为了更好的控制线程的使用,我们可以自定义我们自己的线程池,使用方式@Async(“myThreadPool”)
废话太多,直接上代码:
@Scheduled(fixedRate = 100010,initialDelay = 100020)
@Async(“myThreadPoolTaskExecutor”)
//@Async
public void scheduledTest02(){
System.out.println(Thread.currentThread().getName()+“—>xxxxx—>”+Thread.currentThread().getId());
}
//自定义线程池
@Bean(name = “myThreadPoolTaskExecutor”)
public TaskExecutor getMyThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(20);
taskExecutor.setMaxPoolSize(200);
taskExecutor.setQueueCapacity(25);
taskExecutor.setKeepAliveSeconds(200);
taskExecutor.setThreadNamePrefix(“Haina-ThreadPool-”);
// 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//调度器shutdown被调用时等待当前被调度的任务完成
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//等待时长
taskExecutor.setAwaitTerminationSeconds(60);
taskExecutor.initialize();
return taskExecutor;
}
线程池的使用心得
-
java中提供了ThreadPoolExecutor和ScheduledThreadPoolExecutor,对应与spring中的ThreadPoolTaskExecutor和ThreadPoolTaskScheduler,但是在原有的基础上增加了新的特性,在spring环境下更容易使用和控制。
-
使用自定义的线程池能够避免一些默认线程池造成的内存溢出、阻塞等等问题,更贴合自己的服务特性
-
使用自定义的线程池便于对项目中线程的管理、维护以及监控。
-
即便在非spring环境下也不要使用java默认提供的那几种线程池&