问题
Say I have this:
public void foo(){
CompletableFuture.delayedExecutor(1, TimeUnit.MILLISECONDS).execute(() -> {
doSomethingA();
});
doSomethingB();
}
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?
回答1:
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.
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.
来源:https://stackoverflow.com/questions/54560757/ensure-that-code-within-completablefuture-callback-executes-after