package com.beauty.riskAudit.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @desc: 线程池配置
* @version: 1.0
*/
@Configuration
@EnableAsync
@Slf4j
public class ExecutorConfig {
/**
* 公用线程池配置
* @return
*/
@Bean
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
threadPoolTaskExecutor.setCorePoolSize(5);
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
//最大线程数
threadPoolTaskExecutor.setMaxPoolSize(5);
//配置队列大小
threadPoolTaskExecutor.setQueueCapacity(50);
//配置线程池前缀
threadPoolTaskExecutor.setThreadNamePrefix("async-service-");
//拒绝策略
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
/**
* 项目自定义线程池配置
* @return
*/
@Bean
public Executor customServiceExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
//线程核心数目
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
//最大线程数
threadPoolTaskExecutor.setMaxPoolSize(10);
//配置队列大小
threadPoolTaskExecutor.setQueueCapacity(50);
//配置线程池前缀
threadPoolTaskExecutor.setThreadNamePrefix("custom-service-");
//配置拒绝策略
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//数据初始化
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
// 使用用例
// @Async("customServiceExecutor")
// public void executeHttpRequest(){
// // 业务代码
// }
}
1.需要异步的方法,不与调用方同一个类才可生效。
2.方法内部需对异常进行处理,避免造成线程阻塞。
二、jdk1.8 线程声明
package com.beauty.common.util;
import java.util.concurrent.*;
public class SysExecutorUtils {
private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(50);
private static ExecutorService executorService = Executors.newFixedThreadPool(30);
private static ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();
public static void execute(Runnable runnable) {
executorService.execute(runnable);
}
public static void singleExecute(Runnable runnable){
singleExecutorService.execute(runnable);
}
public ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(runnable, delay, unit);
}
}
1.使用该类个人建议使用 execute()方法。
2.三个类的区别请看源码注释,说的已经很清楚了。