我一直在尝试实现异步过程,其中父方法调用子方法,而子方法又将调用三个不同的方法。我希望所有这些过程都是异步完成的,即在子方法中的这三个调用并行执行后,控件应返回到父方法,并继续执行其其余部分。
我有这段代码,经过测试可以正常工作。
public ReturnSomething parent(){
child();
...//rest to UI
}
private void child(){
ExecutorService executorService = Executors.newFixedThreadPool(3);
Runnable service1 = () -> {
MyFileService.service1();
};
Runnable service2 = () -> {
MyFileService.service2();
};
Runnable service3 = () -> {
MyFileService.service3();
};
executorService.submit(service1);
executorService.submit(service2);
executorService.submit(service3);
}
Run Code Online (Sandbox Code Playgroud)
现在,我的负责人要我改用它。
public ReturnSomething parent(){
child();
...//rest to UI
}
private void child(){
CompletableFuture.supplyAsync(() -> MyFileService.service1();
CompletableFuture.supplyAsync(() -> MyFileService.service2();
CompletableFuture.supplyAsync(() -> MyFileService.service3();
}
Run Code Online (Sandbox Code Playgroud)
我知道CompletableFuture是Java 8的新功能,但是第二代码比第一代码好吗?因为对于ExecutorService,我没有调用“ get()”方法,所以我不会等待aysnc响应。那么,可以请人解释一下有什么区别吗?