1.java给我们自带了4种线程池
newSingleThreadExexcutor:单线程数的线程池(核心线程数=最大线程数=1)
newFixedThreadPool:固定线程数的线程池(核心线程数=最大线程数=自定义)
newCacheThreadPool:可缓存的线程池(核心线程数=0,最大线程数=Integer.MAX_VALUE)
newScheduledThreadPool:支持定时或周期任务的线程池(核心线程数=自定义,最大线程数=Integer.MAX_VALUE
使用方式:
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(() -> {
// 业务逻辑
});
2. 往往我们需要根据业务实际情况自己定义线程池
2.1 创建线程池类:
package com.xxx.xxx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class MyThreadPoolConfig {
@Bean("MyThreadPoolExecutor")
public ThreadPoolExecutor threadPoolExecutor() {
return new ThreadPoolExecutor(
//核心线程数量
16,
//最大线程数量
16,
//最大存活时间
60,
//单位秒
TimeUnit.SECONDS,
//队列类型及大小,
new LinkedBlockingDeque<>(3200),
//线程工厂,构建线程
Executors.defaultThreadFactory(),
//任务具有策略
new ThreadPoolExecutor.AbortPolicy());
}
}
2.2 使用示例:
@Resource
private ThreadPoolExecutor myThreadPoolExecutor;
## 方法中调用
myThreadPoolExecutor.execute(() -> {
// 业务逻辑
})