ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> calculate(Integer input) {
return executor.submit(() -> {
Thread.sleep(3000);
return input * input;
});
}
public static void main(String []args) throws Exception {
Main m = new Main();
System.out.println(m.calculate(5).get());
System.out.println("Main");
我们使用 2 个线程向 Executor 提交 Callable,但是当我告诉
m.calculate(5).get()
它阻塞了主线程。所以,我不明白,何时以及为什么应该使用
Future
如果它阻塞了主线程并且不异步运行?
最佳答案
如果您查看 Future::get
的文档它说:“如有必要,等待计算完成,然后检索其结果。”通过调用此方法,您同意在主线程中等待结果。
您可以通过调用 Future::isDone
检查 Future 是否已完成,它返回 boolean 值。
在您的场景中,它可以像这样使用
public static void main(String []args) throws Exception {
Main m = new Main();
Future<Integer> futureInt = m.calculate(5);
// do some other asynchronous task or something in main thread while futureInt is doing its calculations
// and then call Future::get
int result = futureInt.get();
见:doc
关于java - 为什么这个 Future 的方法阻塞了主线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892686/