我相信很多人需要的是这个吧?copy完先别急着走,往下看。
@Configuration
@ConfigurationProperties(prefix = "thread.pool")
public class ThreadPoolConfig {
private int coreSize = Runtime.getRuntime().availableProcessors() * 2;
private int maxSize = 64;
private int queueCapacity = 1000;
@Bean("taskExecutor")
public Executor taskExecutor() {
//注意这一行日志:2. do submit,taskCount [101], completedTaskCount [87], activeCount [5], queueSize [9]
//这说明提交任务到线程池的时候,调用的是submit(Callable task)这个方法,当前已经提交了101个任务,完成了87个,当前有5个线程在处理任务,还剩9个任务在队列中等待,线程池的基本情况一路了然;
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数10:线程池创建时候初始化的线程数
executor.setCorePoolSize(coreSize);
//最大线程数128:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
//maxPoolSize 当缓冲队列满了以后会增加活动线程数,直到MaxPoolSize;
executor.setMaxPoolSize(maxSize);
//缓冲队列:用来缓冲执行任务的队列
executor.setQueueCapacity(queueCapacity);
//允许线程的空闲时间30秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(30);
//线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("taskExecutor");
//理线程池对拒绝任务的处策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
executor.setRejectedExecutionHandler(rejectedExecutionHandler());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);
executor.initialize();
return executor;
}
public RejectedExecutionHandler rejectedExecutionHandler() {
return (r, executor) -> {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}
public int getQueueCapacity() {
return queueCapacity;
}
public void setQueueCapacity(int queueCapacity) {
this.queueCapacity = queueCapacity;
}
public int getCoreSize() {
return coreSize;
}
public void setCoreSize(int coreSize) {
this.coreSize = coreSize;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
}
坑
ThreadPoolTaskExecutor的MaxPoolSize设计经常会让人产生误区,只有在等待队列满了以后才会增加core线程。感觉这点比较坑,还是数据库连接池的设计好一点。因为当队列满了以后core线程数再增长的话,很可能会来不及,这时就很容易触发拒绝策略。如果你的拒绝策略设置不当很可能带来灾难性的后果。这里推荐上面代码中的拒绝策略,在触发拒绝策略时直接强行塞入等待队列。
一个死锁问题的分析现象:当同时送入线程池的任务大于配置core-size时,会引起程序死锁。
测试代码如下:
public static void main(String[] args) throws InterruptedException {
ThreadPoolTaskExecutor taskExecutor = taskExecutor();
for (int i = 0; i < 3; i++) {
int finalI = i;
taskExecutor.submit(() -> outerCall(taskExecutor, finalI));
}
System.out.println("task push over");
}
public static void outerCall(Executor taskExecutor, int i){
try {
System.out.println("outer " + i);
TimeUnit.SECONDS.sleep(2);
CountDownLatch latch = new CountDownLatch(1);
taskExecutor.execute(() -> {
nestedCall(latch, i);
});
latch.await();
}catch (Exception e){
e.printStackTrace();
}
}
public static void nestedCall(CountDownLatch latch, int i){
System.out.println("nested " + i);
latch.countDown();
}
public static ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(6);
executor.setQueueCapacity(12);
executor.setKeepAliveSeconds(30);
executor.setRejectedExecutionHandler(rejectedExecutionHandler());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(30);
executor.initialize();
return executor;
}
public static RejectedExecutionHandler rejectedExecutionHandler() {
return (r, executor) -> {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}
如果运行main方法会产生什么结果呢,如下:
task push over outer 0 outer 1 outer 2
不会再有新的输出了,程序已经死锁。
为什么呢?
我们来看线程池里边发生的事情(数字的顺序可能是乱的,这里只是其中一种情况):
- 执行outerCall i=0
- 执行outerCall i=1
- 执行outerCall i=2
- 送入等待队列 nestedCall i=0
- 送入等待队列 nestedCall i=1
- 送入等待队列 nestedCall i=2
outerCall的执行占据了所有的活动线程(3个),等待nestedCall完成。然而nestedCall在当前线程池的等待队列中如果outerCall不退出,他永远也得不到执行的机会,死锁了。
结论在使用java线程池的时候要特别注意最好不要有这种嵌套的任务。如果有这种嵌套使用线程池的情况的话一定要保证外层的线程不会等待内层线程完成再返回,或者为等待添加超时时间。



