ThreadPoolTaskExecutor创建线程池
1.前⾔
ThreadPoolTaskExecutor和ThreadPoolExecutor什么关系?
ThreadPoolTaskExecutor是spring core包中的,⽽ThreadPoolExecutor是JDK中的JUC(java.util .concurrent)。
ThreadPoolTaskExecutor是对ThreadPoolExecutor进⾏了封装处理。
来看⼀下ThreadPoolExecutor和ThreadPoolTaskExecutor结构,祖类都是调⽤Executor接⼝:
下⾯是ThreadPoolTaskExecutor 中的部分源码,就使⽤到了ThreadPoolExecutor 。
public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor { private final Object poolSizeMonitor = new Object();
private int corePoolSize = 1;
private int maxPoolSize = 2147483647;
private int keepAliveSeconds = 60;
private int queueCapacity = 2147483647;
private boolean allowCoreThreadTimeOut = false;
@Nullable
private TaskDecorator taskDecorator;
@Nullable
private ThreadPoolExecutor threadPoolExecutor;
private final Map<Runnable, Object> decoratedTaskMap;
关于ThreadPoolExecutor中参数详情看的⽂章。
2.springboot配置使⽤
配置⽂件
@Configuration
@EnableAsync
public class SpringThreadPoolExecutorConfig {
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setKeepAliveSeconds(300);
//核⼼线程池数
pool.setCorePoolSize(50);
//最⼤线程
java线程池创建的四种pool.setMaxPoolSize(100);
//队列容量
pool.setQueueCapacity(1000);
//队列满,线程被拒绝执⾏策略
pool.setRejectedExecutionHandler(new urrent.ThreadPoolExecutor.CallerRunsPolicy());
pool.setThreadNamePrefix("aaaa-common-support-service--");
return pool;
}
Reject策略预定义有四种
ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运⾏时 RejectedExecutionException。
ThreadPoolExecutor.CallerRunsPolicy策略 ,调⽤者的线程会执⾏该任务,如果执⾏器已关闭,则丢弃.
ThreadPoolExecutor.DiscardPolicy策略,不能执⾏的任务将被丢弃.
ThreadPoolExecutor.DiscardOldestPolicy策略,如果执⾏程序尚未关闭,则位于⼯作队列头部的任务将被删除,然后重试执⾏程序(如果再次失败,则重复此过程).
使⽤
@Slf4j
@Service("AService")
public class AServiceImpl implements AService {
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Override
public List<String> queryUserByGivenname(String txNo, String givenname) throws ParamInvalidException {
log.info("-------txNO[{}],givename[{}]", txNo,givenname);
});
return null;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论