1、新增配置类
@Configuration
public class ThreadPoolConfig {
@Value("${thread.pool.corePoolSize}")
private int corePoolSize;
@Value("${thread.pool.maximumPoolSize}")
private int maximumPoolSize;
@Bean(name = "myThreadPool")
public ThreadPoolExecutor myThreadPool() {
return new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
60l,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10),
Executors.defaultThreadFactory(),
new MyRejectPolicy() //自定义拒绝策略
// new ThreadPoolExecutor.AbortPolicy() // 终止策略抛出异常
// new ThreadPoolExecutor.DiscardPolicy() // 抛弃策略无异常
// new ThreadPoolExecutor.DiscardOldestPolicy() // 丢掉最早未处理的任务
// new ThreadPoolExecutor.CallerRunsPolicy() // 交由主线程执行
);
}
}
2、自定义拒绝策略
public class MyRejectPolicy implements RejectedExecutionHandler {
//1、实现 ejectedExecutionHandler 接口
//2、重写 rejectedExecution 方法
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// 核心改造点,由blockingqueue的offer改成put阻塞方法
e.getQueue().put(r);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
3、yml 文件属性配置
thread:
pool:
corePoolSize: 3
maximumPoolSize: 5
4、测试类测试
@SpringBootTest
class OfficeAutoSysApplicationTests {
@Autowired
@Qualifier("myThreadPool")
ThreadPoolExecutor threadPoolExecutor;
@Test
void test_1() {
for (int i = 1; i < 100; i++) {
int task = i;
threadPoolExecutor.execute(() -> {
System.out.println("线程:" + Thread.currentThread().getName() + "正在执行任务" + task);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
}
4、输出结果