这里浅显记录一下@Async注解实现异步操作,对于@Async实现异步来说,它的执行是有条件的,你需要把异步代码块放在单独的类里,这样当spring在注入时,才不会相互影响,别问为什么,就是这样规定的。
1.先创建一个线程池
@Configuration
@EnableAsync
@Slf4j
public class ThreadPoolConfiguration {
@Bean(name = "defaultThreadPoolExecutor", destroyMethod = "shutdown")
public ThreadPoolExecutor systemCheckPoolExecutorService() {
return new ThreadPoolExecutor(5, 6,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
}
2.再创建一个异步业务层类,专门用于存放异步操作的相关代码
@Service
public class AsyncServiceImpl {
@Async("defaultThreadPoolExecutor")
public Boolean execute(Integer num) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
System.out.println("线程:" + Thread.currentThread().getName() + " , 任务:" + num);
return true;
}
}
3.在另一个业务层中调用异步类中的方法
@Service
@Slf4j
public class TestServiceImpl {
@Autowired
private AsyncServiceImpl asyncServiceImpl;
public void test() {
log.info("executeTask Start!");
asyncServiceImpl.execute(5);
log.info("executeTask End!");
}
}
4.结果展示: