java - 工作线程发送到 sleep 后,CompletableFuture没有响应

标签 java multithreading java-8 executorservice fork-join

我正在尝试了解 ConsumableFuture
基本上,我向ConsumableFuture提供了一个任务,然后将运行该任务的辅助线程 hibernate 2秒钟。我希望辅助线程在2秒后恢复执行并返回结果。

public class CompletableFutureDemo {

    public static void main(String[] args) {
        
        System.err.println("Application started");
        
        CompletableFuture
            .supplyAsync(()->work1())
            .thenAccept(op-> System.out.println(op));
        
        System.err.println("Application ended");
    }
    
    public static int work1() {
        System.out.println(Thread.currentThread().getName());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("work1 called");
        return (int) (Math.random() * 100);
    }
}
输出:
Application started
ForkJoinPool.commonPool-worker-1
Application ended
为什么工作线程不恢复?
但是,如果我从工作线程中删除sleep语句,那么我将获得所需的输出。
Application started
ForkJoinPool.commonPool-worker-1
work1 called
Application ended
64

最佳答案

正如@Slaw在注释中已经指出的那样,主线程完成,并在工作线程处于 sleep 状态时退出应用程序,因此您可以调用join来保持主线程等待,直到工作线程完成。

System.err.println("Application started");

 CompletableFuture
            .supplyAsync(()->work1())
            .thenAccept(op-> System.out.println(op)).join();

System.err.println("Application ended");
输出 :
ForkJoinPool.commonPool-worker-3
Application started
work1 called
12
Application ended
或者您可以在完成工作后让主线程等待
  System.err.println("Application started");

  CompletableFuture<Void> completableFuture = CompletableFuture
            .supplyAsync(()->work1())
            .thenAccept(op-> System.out.println(op));

  System.err.println("Application ended");

  completableFuture.join();
输出 :
ForkJoinPool.commonPool-worker-3
Application started
Application ended
work1 called
25
如果您有多个CompletableFuture对象,则可以使用allOf等待所有任务完成(但是在后台,每个可完成任务将异步执行)
CompletableFuture.allOf(completableFuture1,completableFuture1).join();

关于java - 工作线程发送到 sleep 后,CompletableFuture没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65740949/

相关文章:

C++ - For 循环有时不会停止 - 多线程

c++ - 简单快速读取过程

java - 限制在Android移动模拟器上运行Android应用程序

java - 使用java正则表达式当模式包含左括号时如何替换所有

java - 检测到有缺陷的 token (机制级别 : Defective token detected (Mechanism level: Invalid SPNEGO NegTokenTarg token : Short read of DER length))

java - 在 Java 中使用 .stream() 比较整数

java - 为什么方法引用不是单例的?

java - 如何通过 Selenium WebDriver 使用 ChromeOptions 禁用通知

java - 多个流中批量写入mongoDB时出错

java - 用另一个对象列表填充列表