如何同步运行两个异步任务

我是 java(springboot) 中多线程概念的新手,有一个场景需要解决。有一个函数,其中调用了 2 个异步函数。我想让它们同步执行。例如:


public void func(){


call1();

call2();

}


@Async

public void call1(){}


@Async

public void call2(){}

任何人都可以建议一种方法来实现此功能。


梦里花落0921
浏览 296回答 2
2回答

一只甜甜圈

您可以等待@Async方法,如果你改变他们返回Future。例如像这样:@Componentclass AsyncStuff {&nbsp; &nbsp; @Async&nbsp; &nbsp; public ListenableFuture<?> call1() {&nbsp; &nbsp; &nbsp; &nbsp; /** do things */&nbsp; &nbsp; &nbsp; &nbsp; return AsyncResult.forValue(null);&nbsp; &nbsp; }&nbsp; &nbsp; @Async&nbsp; &nbsp; public ListenableFuture<?> call2() {&nbsp; &nbsp; &nbsp; &nbsp; /** do other things */&nbsp; &nbsp; &nbsp; &nbsp; return AsyncResult.forValue(null);&nbsp; &nbsp; }}@Componentclass User {&nbsp; &nbsp; @Autowired&nbsp; &nbsp; AsyncStuff asyncStuff; // @Async methods work only when they are in a different class&nbsp; &nbsp; public void use() throws InterruptedException, ExecutionException {&nbsp; &nbsp; &nbsp; &nbsp; asyncStuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .call1() // starts this execution in another thread&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .get();&nbsp; // lets this thread wait for the other thread&nbsp; &nbsp; &nbsp; &nbsp; asyncStuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .call2() // now start the seconds thing&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .get();&nbsp; // and wait again&nbsp; &nbsp; }}但它保证比简单地在没有异步的情况下执行所有这些操作要慢,因为所有这些都增加了在线程之间移动执行的开销。调用线程可以代替等待其他线程做事情,而只是在那个时候执行代码本身。

莫回无

不完全确定这里的动机是什么,但是从我从问题中可以理解的内容来看,目标似乎是您不想阻塞主线程(线程执行 func()),同时实现 call1 的串行执行() 和 call2()。如果这就是你想要的,你也许可以使 call1() 和 call2() 同步(即删除@Async 注释),并添加第三个异步方法(可能是 callWrapper()),并依次调用 call1() 和 call2()在那个方法中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java