如何确保在使用返回结果之前执行异步方法?

我有包含两个异步方法的 AsyncService 类。


@Service

public class AsyncService {

    @Async

    public HashMap<int, Student> studentMap(List<String> students) {

        //contains database call

        return result1;

    }


    @Async

    public HashMap<int, Teacher> teacherMap(List<String> teachers) {

        //contains database call

        return result2;

    }

}

这两个方法是从 UserService 类调用的。


@Service

public class UserService {

    public List<User> doJob () {

        HashMap<int, Student> = asyncService.studentMap(students);

        HashMap<int, Teacher> = asyncService.teacherMap(teachers);

        // now work with these HashMap

    }

}

我想确保当我使用这两个异步调用的返回结果时,两个异步方法都完成了。我怎样才能做到这一点?我知道完整的未来可以在这里解决。但我不确定如何在这里使用它。还有其他解决方案吗?我正在使用弹簧靴。


小唯快跑啊
浏览 139回答 2
2回答

神不在的星期二

@Async注释假设被注释的方法返回Future.&nbsp;有一个Future你刚才有没有其他的方式来使用的结果,除了调用Future.get()它returs异步过程完成后严格。也就是说,正确实现异步服务,你就没有麻烦了。

守着星空守着你

你可以用CompletableFuture. 下面是一个例子:CompletableFuture.allOf(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CompletableFuture.runAsync(() ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;asyncService.studentMap(students);//make it synchronized call&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CompletableFuture.runAsync(() ->&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;asyncService.teacherMap(teachers);// make it synchronized call&nbsp; &nbsp; &nbsp; &nbsp; ).thenRun(() -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do after complete 2 async call.&nbsp; &nbsp; &nbsp; &nbsp; }).get();您的服务呼叫需要同步:@Servicepublic class AsyncService {public Hashmap<int, Student> studentMap(List<String> students) {&nbsp; &nbsp; //contains database call&nbsp; &nbsp; return result1;}public Hashmap<int, Teacher> teacherMap(List<String> teachers) {&nbsp; &nbsp; //contains database call}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java