- 我的技术博客:https://nezha.github.io,https://nezhaxiaozi.coding.me
- 我的简书地址:https://www.jianshu.com/u/a5153fbb0434
本文的代码地址:GitHub Async Demo
自定义一个 @Async
异步的策略
1.ExecutorConfig
@Configuration
@EnableAsync
public class ExecutorConfig {
private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
private int corePoolSize = 10;
private int maxPoolSize = 10; //线程池的大小
private int queueCapacity =20;//排队队列长度
@Bean
public AsyncTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("Anno-Executor");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
logger.info("taskExecutor initialize");
return executor;
}
}
2.UserService
@Service
public class UserService {
@Async
public void sayHello(int number) throws InterruptedException{
Thread.sleep(2000L);
System.out.println(">>>>"+number+">>>>");
}
}
3.AsyncApplicationTests
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAsync
public class AsyncApplicationTests {
@Autowired
private UserService userService;
@Test
public void testAsync() throws InterruptedException{
for (int i = 0; i < 20; i++) {
userService.sayHello(i);
Thread.sleep(1500);
}
}
}
网友评论