一、线程池的创建
/**
* 线程池创建
*/
@Configuration
@EnableAsync
public class ExecutorCreater {
//核心线程数
private static final int CORE_POOL_SIZE = 5;
//最大线程数
private static final int MAX_POOL_SIZE = 5;
//队列大小
private static final int QUEUE_CAPACITY = 2000;
//线程池中的线程的名称前缀
private static final String NAME_PREFIX = "async-service-";
/**
* 创建线程池
*/
@Bean(name = "asyncServiceExecutor")
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(CORE_POOL_SIZE);
//配置最大线程数
executor.setMaxPoolSize(MAX_POOL_SIZE);
//配置队列大小
executor.setQueueCapacity(QUEUE_CAPACITY);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix(NAME_PREFIX);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
/**
* 线程池任务分发,无返回值
*/
public CompletableFuture<Void> myRunAsync(Runnable runnable){
return CompletableFuture.runAsync(runnable,asyncServiceExecutor());
}
/**
* 线程池任务分发,有返回值
*/
public CompletableFuture mySupplyAsync(Supplier supplier){
return CompletableFuture.supplyAsync(supplier,asyncServiceExecutor());
}
}
二、调用方式
举例:
@Service
public class TestServiceImpl implements ITestService {
@Autowired
private ExecutorCreater executorCreater;
public void testExecutor() throws Exception {
//任务1
CompletableFuture<Void> future1 = executorCreater.myRunAsync(() -> {
try {
Thread.sleep(5000);
System.out.println("111");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//任务2
CompletableFuture<Void> future2 = executorCreater.myRunAsync(() -> {
try {
Thread.sleep(1000);
System.out.println("222");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
//任务3
CompletableFuture<Void> future3 = executorCreater.myRunAsync(() -> {
try {
Thread.sleep(3000);
System.out.println("333");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
CompletableFuture<Void> cfAll = CompletableFuture.allOf(future1, future2, future3);
System.out.println("cfAll结果->" + cfAll.get());
}