系统中有个定时器,针对每个用户定时生成报告。但是每个报告需要消耗3~5秒,所以在定时器里不能去处理,然后就想到线程池,在定时器里只需要启动线程就行了,所有业务全在另起的线程里进行。
spring的配置如下
<-- 队列集合 --> <-- 线程池 -->
java代码
import java.util.concurrent.BlockingQueue;import java.util.concurrent.RejectedExecutionHandler;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;public class AsyncExecutorService { private ThreadPoolExecutor executorService; private RejectedExecutionHandler rejectionHandler; private BlockingQueueblockingQueue; private int defaultCoreSize; private int defaultMaxSize; private long defaultKeepAliveTime; public RejectedExecutionHandler getRejectionHandler() { return rejectionHandler; } public void setRejectionHandler(RejectedExecutionHandler rejectionHandler) { this.rejectionHandler = rejectionHandler; executorService.setRejectedExecutionHandler(rejectionHandler); } public BlockingQueue getBlockingQueue() { return blockingQueue; } public void setBlockingQueue(BlockingQueue blockingQueue) { this.blockingQueue = blockingQueue; } public ThreadPoolExecutor getExecutorService() { return executorService; } public void setExecutorService(ThreadPoolExecutor executorService) { this.executorService = executorService; this.defaultCoreSize = this.executorService.getCorePoolSize(); this.defaultMaxSize = this.executorService.getMaximumPoolSize(); this.defaultKeepAliveTime = this.executorService.getKeepAliveTime(TimeUnit.SECONDS); } public void execute(Runner runner){ executorService.execute(runner); } public void resizePoolMaxSize(int maxSize){ this.executorService.setMaximumPoolSize(maxSize); } public void resizePoolCoreSize(int coreSize){ this.executorService.setMaximumPoolSize(coreSize); } public void resetPoolAliveTime(long aliveTime){ this.executorService.setKeepAliveTime(aliveTime, TimeUnit.SECONDS); } public void resetDefault(){ this.executorService.setCorePoolSize(this.defaultCoreSize); this.executorService.setMaximumPoolSize(this.defaultMaxSize); this.executorService.setKeepAliveTime(this.defaultKeepAliveTime, TimeUnit.SECONDS); } @PostConstruct public void init(){ //asyncExecutorService will be init !!! } @PreDestroy public void destroy(){ //asyncExecutorService will be destroyed !!! executorService.shutdown(); } public Integer getPoolMaxSize() { return executorService.getMaximumPoolSize(); }}
测试(调用)代码
public class Test{ @Autowired private AsyncExecutorService asyncExecutorService; public void startTask(){ asyncExecutorService.execute(()->{ syso("run"); }); } }