Java中的@Async异步功能详解
Java中的@Async异步功能详解
@Async注解,可以实现异步处理的功能,它可以有返回值,或者直接在新线程时并行执行一个任务,对于异步来说,它的执行是有条件的,你需要把异步代码块放在单独的类里,当spring在注入时,才不会相互影响,因为异步是一个比较特殊的代理。
异步入口
@EnableAsync
具体的异步方法
/**
* 异常的类型应该和同步执行的类分开,这样在ioc建立时不会相互干扰
*/
@Service
public class MessageService {
@Async
public void msg1() throws Exception {
Thread.sleep(5000L);
System.out.println("async1:" + LocalDateTime.now() +
",id:" + Thread.currentThread().getId());
}
}上面代码中的异步,是一个没有返回值的,一般像发送消息可以采用这种方式。
带有返回值的异步
@Async
public Future<String> asyncMethodWithReturnType() {
System.out.println("Execute method asynchronously - "
+ Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<String>("hello world !!!!");
} catch (InterruptedException e) {
//
}
return null;
}这种会返回一个委托对象Future,我们如果希望得到它的返回时,需要在主程序中去监听它,就是写在循环,去等待它的返回结果。
Future<String> future = messageService.asyncMethodWithReturnType();
while (true) { ///这里使用了循环判断,等待获取结果信息
if (future.isDone()) { //判断是否执行完毕
System.out.println("Result from asynchronous process - " + future.get());
break;
}
System.out.println("Continue doing something else. ");
System.out.println("main end:" + LocalDateTime.now() +
",id:" + Thread.currentThread().getId());
}上面代码主程序在执行到异步方法时,由于遇到了while(true),所以会租塞,直到有返回结果为止。
到此这篇关于Java中的@Async异步功能详解的文章就介绍到这了,更多相关@Async异步功能内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot中的@ApiModelProperty注解作用
这篇文章主要介绍了SpringBoot中的@ApiModelProperty注解作用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教。2022-01-01
Spring中的DeferredImportSelector实现详解
这篇文章主要介绍了Spring中的DeferredImportSelector实现详解,两个官方的实现类AutoConfigurationImportSelector和ImportAutoConfigurationImportSelector都是Spring Boot后新增的实现,需要的朋友可以参考下2024-01-01
java工厂实例BeanFactoryPostProcessor和BeanPostProcessor区别分析
这篇文章主要为大家介绍了BeanFactoryPostProcessor和BeanPostProcessor区别示例分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-07-07
JPA @ManyToMany 报错StackOverflowError的解决
这篇文章主要介绍了JPA @ManyToMany 报错StackOverflowError的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12


最新评论