1.配置:
<!-- spring thread pool executor -->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 線程池維護線程的最少數量 -->
<property name="corePoolSize" value="5" />
<!-- 允許的空閒時間 -->
<property name="keepAliveSeconds" value="200" />
<!-- 線程池維護線程的最大數量 -->
<property name="maxPoolSize" value="10" />
<!-- 緩存隊列 -->
<property name="queueCapacity" value="20" />
<!-- 對拒絕task的處理策略 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
/**
*多線程併發處理demo
* @author stone
*/
public class MultiThreadDemo implements Runnable{
@Override
public void run() {
System.out.println("success");
}
}
@Component
public class Test {
@Resource
private ThreadPoolTaskExecutor taskExecutor;
public void test(){
taskExecutor.execute(new MultiThreadDemo());
}
2.構建bean方式
@Component
@Scope
public class PresaleFailExecutePoll {
// @Value(value = "${presale.core.poll.size}")
private int corePoolSize = 20;
// @Value(value = "${presale.max.poll.size}")
private int maxPoolSize = 40;
// @Value(value = "${presale.quenue.capacity}")
private int queueCapacity = 50;
// @Value(value = "${presale.keep.alive.seconds}")
private int keepAliveSeconds = 300;
@Bean
public Executor presaleFailAsyncPool() {
System.out.println("The presaleFailAsyncPool start to initialize ...");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心線程池大小
executor.setCorePoolSize(corePoolSize);
//最大線程數
executor.setMaxPoolSize(maxPoolSize);
//隊列容量
executor.setQueueCapacity(queueCapacity);
// 活躍時間
executor.setKeepAliveSeconds(keepAliveSeconds);
// 線程名字前綴
executor.setThreadNamePrefix("MyExecutor-");
// setRejectedExecutionHandler:當pool已經達到max size的時候,如何處理新任務
// CallerRunsPolicy:不在新線程中執行任務,而是由調用者所在的線程來執行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
@Async("presaleFailAsyncPool") //即配置線程池的方法名,此處如果不寫自定義線程池的方法名,會使用默認的線程池
public void delPresaleOrder(Long shuttleId) {
}