【发布时间】:2019-07-23 13:00:25
【问题描述】:
我正在尝试使用 Java 8 的 CompletableFuture 功能,该功能说它提供了异步运行的能力。但是为了执行“未来”需要调用future.get() 方法。这样做会阻塞主线程。因为它在执行future.get()之后的行之前等待30秒睡眠
有没有办法做到这一点?执行非阻塞方式 我正在尝试打印
“我将在主线程中运行。”
之前
“我将在与主线程不同的线程中运行。”
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
// Simulate a long-running Job
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
System.out.println("I'll run in a separate thread than the main thread.");
}
});
future.get();
System.out.println("I'll run in the main thread.");
}
【问题讨论】:
-
future.get()正在阻塞主线程,因此线程打印语句将始终位于主线程打印之前 -
你可以移动主打印语句 before
future.get()但这似乎很简单,所以我不完全确定你的实际问题是什么 -> 你为什么需要 main-action 出现在 thread-action 之前 -
CompletableFuture.runAsync(已经开始运行您的其他线程。调用future.get()只是等待该线程完成运行并获得其结果,然后再继续执行调用的线程 -
CompletableFuture正在非阻塞运行 -
@ShenaliSilva 当您删除
get()调用时,主线程不会被阻塞,因为在您的简化示例中没有其他内容,它将退出。当只剩下守护线程时,JVM 将终止,这就是您可能会或可能不会看到打印消息的原因,具体取决于不可预测的时间。这不是现实生活中的应用问题。但是当您简化的示例在后台线程中打印消息时,您必须等待才能终止。
标签: java multithreading java-8 future completable-future