我正在尝试使用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.");
}发布于 2019-03-01 13:36:28
CompletableFuture.runAsync(Runnable)已经开始运行其他线程了。调用future.get()只是等待线程完成运行并获得其结果的一种方式,然后在线程中继续执行调用。
当您立即启动线程并执行get时,没有在线程之间执行任何操作(就像您所做的那样),那么运行线程就没有意义了。
https://stackoverflow.com/questions/54945572
复制相似问题