创建线程池的四种方式
Executors.newCachedThreadPool() 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
阿里规约:
【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,
这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
关于ThreadPoolExecutor 和 ThreadPoolTaskExecutor 区别
ThreadPoolExecutor是一个java类不提供spring生命周期和参数装配。
ThreadPoolTaskExecutor实现了InitializingBean, DisposableBean ,xxaware等,具有spring特性
简单理解:
1、ThreadPoolTaskExecutor使用ThreadPoolExecutor并增强,扩展了更多特性
2、ThreadPoolTaskExecutor只关注自己增强的部分,任务执行还是ThreadPoolExecutor处理。
3、前者spring自己用着爽,后者离开spring我们用ThreadPoolExecutor爽。
注意:ThreadPoolTaskExecutor 不会自动创建ThreadPoolExecutor需要手动调initialize才会创建
如果@Bean 就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize
本文使用spring的ThreadPoolTaskExecutor
一、自定义线程池
@Configuration
public class ThreadPoolConfig {
// 核心线程数
private int corePoolSize = 5;
// 最大线程数
private int maxPoolSize = 10;
// 队列大小
private int queueSize = 100;
// 线程最大空闲时间
private int keepAliveSeconds = 100;
/**
* 自定义消费队列线程池
* CallerRunsPolicy 这个策略重试添加当前的任务,他会自动重复调用 execute() 方法,直到成功。
* AbortPolicy 对拒绝任务抛弃处理,并且抛出异常。
* DiscardPolicy 对拒绝任务直接无声抛弃,没有异常信息。
* DiscardOldestPolicy 对拒绝任务不抛弃,而是抛弃队列里面等待最久的一个线程,然后把拒绝任务加到队列。
* @return
*/
@Bean(value = "testThreadPool")
public ThreadPoolTaskExecutor buildFirstThreadPool() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(corePoolSize);
threadPool.setMaxPoolSize(maxPoolSize);
threadPool.setQueueCapacity(queueSize);
threadPool.setThreadNamePrefix("testThreadPool-");
threadPool.setKeepAliveSeconds(keepAliveSeconds);
threadPool.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());
//如果@Bean 就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize
// threadPool.initialize();
return threadPool;
}
}
二、具体逻辑实现
@RequestMapping("/test")
public String test(){
System.out.println("请求接口开始----->"+ LocalDateTime.now());
CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("task1 线程name-->" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, taskExecutor);
CompletableFuture<Void> task2 = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
System.out.println("task2 线程name-->" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}, taskExecutor);
try {
CompletableFuture.allOf(task1, task2).get();
System.out.println("请求接口结束----->"+ LocalDateTime.now());
} catch (Exception e) {
e.printStackTrace();
}
return "ok";
}
此外,多个任务可封装多个Runable 类,创建TaskList
//task任务
private class Task implements Runnable{
@Override
public void run() {
//具体业务
}
}
Task task1 = new Task();
Task task2 = new Task();
List<Runnable> taskList = new ArrayList<>();
taskList.add(task1);
taskList.add(task2);
CompletableFuture<?>[] futures = taskList.stream().map(e -> CompletableFuture.runAsync(e, customExecutor))
.collect(Collectors.toSet()).toArray(new CompletableFuture[]{});
CompletableFuture.allOf(futures).get();