通过之前三篇关于Spring Boot异步任务实现的博文,我们分别学会了:
今天我们继续对异步任务的实现进行完善和优化!
如果你已经看过上面几篇内容并已经掌握之后,一起来思考下面这个问题:
假设,线程池配置为核心线程数2、最大线程数2、缓冲队列长度2。此时,有5个异步任务同时开始,会发生什么?
场景重现
我们先来把上面的假设用代码实现一下:
第一步:创建Spring Boot应用,根据上面的假设写好线程池配置。
@EnableAsync
@SpringBootApplication
public class Chapter78Application {
public static void main(String[] args) {
SpringApplication.run(Chapter78Application.class, args);
}
@EnableAsync
@Configuration
class TaskPoolConfig {
@Bean
public Executor taskExecutor1() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(2);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix(“executor-1-”);
return executor;
}
}
}
第二步:用@Async
注解实现一个部分任务
@Slf4j
@Component
public class AsyncTasks {
public static Random random = new Random();
@Async(“taskExecutor1”)
public CompletableFuture doTaskOne(String taskNo) throws Exception {
log.info(“开始任务:{}”, taskNo);
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info(“完成任务:{},耗时:{} 毫秒”, taskNo, end - start);
return CompletableFuture.completedFuture(“任务完成”);
}
}
第三步:编写测试用例
@Slf4j
@SpringBootTest
public class Chapter78ApplicationTests {
@Autowired
private AsyncTasks asyncTasks;
@Test
public void test2() throws Exception {