1.配置spring 线程池
@Configuration
@EnableAsync
@ConfigurationProperties(prefix="threadpool")
public class ExecutePoolConfiguration {
@Value("${threadpool.core-pool-size}")
private int corePoolSize;
@Value("${threadpool.max-pool-size}")
private int maxPoolSize;
@Value("${threadpool.queue-capacity}")
private int queueCapacity;
@Value("${threadpool.keep-alive-seconds}")
private int keepAliveSeconds;
@Bean(name="threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setKeepAliveSeconds(keepAliveSeconds);
pool.setCorePoolSize(corePoolSize);//核心线程池数
pool.setMaxPoolSize(maxPoolSize); // 最大线程
pool.setQueueCapacity(queueCapacity);//队列容量
pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()); //队列满,线程被拒绝执行策略
return pool;
}
}
2.在配置文件里面增加配置
threadpool:
core-pool-size: 30
max-pool-size: 40
queue-capacity: 1000
keep-alive-seconds: 300
3.实现多线程
@Component
public class Demo {
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public void test() {
List<Integer> array = new ArrayList<Integer>();
for(int i=1;i<1000;i++) {
array.add(i);
}
//把上述1000条数据,分5个线程处理
averageAssign(array,5).forEach(
l -> threadPoolTaskExecutor.execute(
()->l.forEach(
m ->System.out.println(m
)
)
)
);
}
public <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remainder = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List<T> value = null;
if (remainder > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remainder--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}
}