【发布时间】:2021-01-15 17:39:04
【问题描述】:
我正在尝试了解 ConsumableFuture。 基本上,我向 ConsumableFuture 提供一个任务,然后让运行该任务的工作线程休眠 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
为什么工作线程没有恢复?
但如果我从工作线程中删除睡眠语句,那么我会得到所需的输出。
Application started
ForkJoinPool.commonPool-worker-1
work1 called
Application ended
64
【问题讨论】:
-
普通 fork-join 池使用守护线程。您的应用程序正在退出,因为主线程(在这种情况下只有非守护线程)在其他线程完成之前退出。
-
@Slaw 感谢您提供的信息。 Fork-join 默认使用守护线程?有什么办法可以防止它们标记为守护进程?
标签: java multithreading java-8 executorservice fork-join