Java 在CompletableFuture中使用thenXXXX与thenXXXXAsync方法对性能的影响
我对使用JDK 8的CompletableFuture类的thenXXXX和thenXXXXAsync方法有疑问。据我所知,应用程序将使用与早期future执行相同的线程,而应用程序同步程序使用池中的任何线程 代码1:Java 在CompletableFuture中使用thenXXXX与thenXXXXAsync方法对性能的影响,java,multithreading,performance,java-8,completable-future,Java,Multithreading,Performance,Java 8,Completable Future,我对使用JDK 8的CompletableFuture类的thenXXXX和thenXXXXAsync方法有疑问。据我所知,应用程序将使用与早期future执行相同的线程,而应用程序同步程序使用池中的任何线程 代码1: CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors) .thenApply(a -> {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors)
.thenApply(a -> {
logger.log(Level.INFO, "Thread Id - 1 " + Thread.currentThread().getName());
////Some operations
})
.thenApply(a -> {
logger.log(Level.INFO, "Thread Id - 2 " + Thread.currentThread().getName());
////Some operations
});
CompletableFuture cf=CompletableFuture.supplyAsync(()->tcf.task(“第一”),执行者)
。然后应用(a->{
logger.log(Level.INFO,“线程Id-1”+Thread.currentThread().getName());
////一些操作
})
。然后应用(a->{
logger.log(Level.INFO,“线程Id-2”+Thread.currentThread().getName());
////一些操作
});
输出:线程Id-1:pool-1-Thread-1 线程Id-2:pool-1-Thread-1 代码2:
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors)
.thenApplyAsync(a -> {
logger.log(Level.INFO, "Thread Id - 1 " + Thread.currentThread().getName());
////Some operations
}, executors)
.thenApplyAsync(a -> {
logger.log(Level.INFO, "Thread Id - 2 " + Thread.currentThread().getName());
////Some operations
}, executors);
CompletableFuture cf=CompletableFuture.supplyAsync(()->tcf.task(“第一”),执行者)
.然后应用同步(a->{
logger.log(Level.INFO,“线程Id-1”+Thread.currentThread().getName());
////一些操作
},遗嘱执行人)
.然后应用同步(a->{
logger.log(Level.INFO,“线程Id-2”+Thread.currentThread().getName());
////一些操作
},遗嘱执行人);
输出:线程Id-1:pool-1-Thread-2 线程Id-2:pool-1-Thread-3 使用哪种方法最好?在代码2中,任务从一个线程移动到另一个线程。它会影响性能吗
谢谢
然后应用
不会保证使用的线程。它可能是完成此未来的线程,但也可能是调用方的线程,例如,当未来已经完成时,或者是调用然后…
方法的任意其他线程,如果这些调用和完成同时发生。问题是,你能忍受这种缺乏控制的情况吗?例如,你对当前线程中完全发生的此操作是否满意。然后应用
不会保证所使用的线程。它可能是完成此未来的线程,但也可能是调用方的线程,例如,当未来已经完成时,或者是调用然后…
方法的任意其他线程,如果这些调用和完成同时发生。问题是,你能忍受这种缺乏控制的情况吗?例如,你对当前线程中完全发生的这种行为感到满意吗。