2 回答
![?](http://img1.sycdn.imooc.com/56fb3e3d0001a10301000100-100-100.jpg)
TA贡献1836条经验 获得超5个赞
您可以等待@Async方法,如果你改变他们返回Future。例如像这样:
@Component
class AsyncStuff {
@Async
public ListenableFuture<?> call1() {
/** do things */
return AsyncResult.forValue(null);
}
@Async
public ListenableFuture<?> call2() {
/** do other things */
return AsyncResult.forValue(null);
}
}
@Component
class User {
@Autowired
AsyncStuff asyncStuff; // @Async methods work only when they are in a different class
public void use() throws InterruptedException, ExecutionException {
asyncStuff
.call1() // starts this execution in another thread
.get(); // lets this thread wait for the other thread
asyncStuff
.call2() // now start the seconds thing
.get(); // and wait again
}
}
但它保证比简单地在没有异步的情况下执行所有这些操作要慢,因为所有这些都增加了在线程之间移动执行的开销。调用线程可以代替等待其他线程做事情,而只是在那个时候执行代码本身。
![?](http://img1.sycdn.imooc.com/5458662500019a7c02200220-100-100.jpg)
TA贡献1865条经验 获得超7个赞
不完全确定这里的动机是什么,但是从我从问题中可以理解的内容来看,目标似乎是您不想阻塞主线程(线程执行 func()),同时实现 call1 的串行执行() 和 call2()。如果这就是你想要的,你也许可以使 call1() 和 call2() 同步(即删除@Async 注释),并添加第三个异步方法(可能是 callWrapper()),并依次调用 call1() 和 call2()在那个方法中。
添加回答
举报