作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在 CompletableFuture 的 supplyAsync() 中处理长时间运行的操作,并将结果放入 thenAccept()。有时 thenAccept() 在主线程上执行,但有时它在工作线程上运行。但我只想在主线程上运行 thenAccept() 操作。这是示例代码。
private void test() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync | I am running on : " + Thread.currentThread().getName());
return "Hello world";
}, executorService);
CompletableFuture<Void> cf3 = cf1.thenAccept(s -> {
System.out.print("thenAccept | I am running on : " + Thread.currentThread().getName());
System.out.println(" | answer : " + s);
});
cf3.thenRun(() -> {
System.out.println("thenRun | I am running on : " + Thread.currentThread().getName());
System.out.println();
});
}
public static void main(String[] args) {
App app = new App();
for(int i = 0; i < 3; i++){
app.test();
}
}
结果是:
supplyAsync | I am running on : pool-1-thread-1
thenAccept | I am running on : main | answer : Hello world
thenRun | I am running on : main
supplyAsync | I am running on : pool-2-thread-1
thenAccept | I am running on : main | answer : Hello world
thenRun | I am running on : main
supplyAsync | I am running on : pool-3-thread-1
thenAccept | I am running on : pool-3-thread-1 | answer : Hello world
thenRun | I am running on : pool-3-thread-1
我该如何解决这个问题?
最佳答案
查看 CompletableFuture 的 JavaDoc .有趣的部分是关于 CompletionStage 政策的部分。
您会发现使用非异步 方法会导致一种非此即彼的情况。如果您随后查看实现,您将最终进入 Java 运行时的非公共(public)部分。有一些 UNSAFE 处理意味着可能会发生某种竞争条件。
我建议使用 thenAcceptAsync() 和 thenRunAsync() 变体并将您的 executorService 变量传递给这两个调用。
关于java - 为什么 CompletableFuture 的 thenAccept() 没有在主线程上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981432/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!