为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梦里花落0921 2021-08-19 18:45:06
我是 java(springboot) 中多线程概念的新手,有一个场景需要解决。有一个函数,其中调用了 2 个异步函数。我想让它们同步执行。例如:public void func(){call1();call2();}@Asyncpublic void call1(){}@Asyncpublic void call2(){}任何人都可以建议一种方法来实现此功能。
查看完整描述

2 回答

?
一只甜甜圈

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

    }

}

但它保证比简单地在没有异步的情况下执行所有这些操作要慢,因为所有这些都增加了在线程之间移动执行的开销。调用线程可以代替等待其他线程做事情,而只是在那个时候执行代码本身。


查看完整回答
反对 回复 2021-08-19
?
莫回无

TA贡献1865条经验 获得超7个赞

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


查看完整回答
反对 回复 2021-08-19
  • 2 回答
  • 0 关注
  • 255 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信