确保CompletableFuture回调中的代码在之后执行 [英] Ensure that code within CompletableFuture callback executes after

查看:403
本文介绍了确保CompletableFuture回调中的代码在之后执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个

public void foo(){
     CompletableFuture.delayedExecutor(1, TimeUnit.MILLISECONDS).execute(() -> {                 
         doSomethingA();                
      });       
      doSomethingB();        
}

是否可以保证doSomethingB();将始终在doSomethingA();之前运行? 线程抢占告诉我,有可能(虽然不太可能)首先运行doSomethingA()?

Is there any guarantee that doSomethingB(); will always run before doSomethingA();? Something tells me with thread pre-emption, it's possible, although unlikely, that doSomethingA() could be run first?

推荐答案

否,不能保证在具有多个处理器的计算机上,doSomethingB()将始终在doSomethingA()之前执行 。虽然很可能会在99.999999999%的时间发生。

No, there is no guarantee, when on a machine which has multiple processors, that doSomethingB() would always execute before doSomethingA(). Though it will likely happen 99.999999999% of the time.

在您的某些评论中,我注意到对事件循环的引用。在Java中,没有像Node和Javascript这样的事件循环本机概念。如果您有4个线程,四个处理器,并且提交了四个任务,则所有四个任务将并行运行。

I noticed in some of your comments a reference to an "Event Loop". In Java there is no native concept of an Event Loop like there is in, say, Node and Javascript. If you have 4 threads, with four processors, and you submit four tasks, all four tasks will run in parallel.

这篇关于确保CompletableFuture回调中的代码在之后执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆