@EnableAsync @Configuration public class TaskPoolConfig { @Bean("taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(200); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("taskExecutor-"); executor.setWaitForTasksToCompleteOnShutdown(true);//设置线程在任务执行完之后才x释放 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; } }
使用Future来获取Runable的执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13
@Slf4j @Component public class Task { public static Random random = new Random(); @Async("taskExecutor") public Future<String> run() throws Exception { long sleep = random.nextInt(10000); log.info("开始任务,需耗时:" + sleep + "毫秒"); Thread.sleep(sleep); log.info("完成任务"); return new AsyncResult<>("test"); } }
定义超时时间并释放线程
1 2 3 4 5 6 7 8 9 10 11 12 13
@Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class ApplicationTests { @Autowired private Task task; @Test public void test() throws Exception { Future<String> futureResult = task.run(); String result = futureResult.get(5, TimeUnit.SECONDS); log.info(result); } }