我正在使用ExecutorService来创建一个线程池 . 添加所有任务后,threadPool将关闭 .
现在Future.get()的Java Doc说
如果需要等待计算完成,然后检索其结果 .
我无法理解“必要时”部分 . future.get()方法何时等待以及等待多长时间?如果等到线程执行结束,是否需要threadPool.awaitTermination?
ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads);
List<Future<?>> futureObjList = new ArrayList<Future<?>>();
for (int i = 0; i < numberOfThreads; i++) {
...
Future<?> future = threadPool.submit(myThread);
futureObjList.add(future);
...
}
threadPool.shutdown();
for(Future<?> future : futureObjList){
try {
future.get();
} catch (Exception e1) {
//if any thread fails, all other thread should stop their execution.
threadPool.shutdownNow();
}
}
try {
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e1) {
throw e1;
}
3 回答
"if necessary"只是意味着
get()
方法可能阻止或不依赖于Runnable
或Callable
中发生的事情是否已经完成 .假设您将一个Callable提交给执行者服务 .
Callable
需要2秒才能执行 .如果在提交后1秒钟调用
get()
,则get()
将再次阻止1秒 . 但是,如果您在提交后5秒钟调用get()
,则get()不会阻止并立即返回 .将阻塞调用线程,如果Callable的方法.call没有返回结果的时间.get被调用 . 如果迭代每个未来,那么当你退出for循环时,所有线程都已完成执行 .
在从线程获取结果之前,您必须调用
threadPool.awaitTermination()
,因为awaitTermination将等待所有线程完成计算 . 完成所有线程后,您可以确保future.get()
在完成执行后不会阻塞 .future.get()
将等待线程完成执行,除非您指定超时 .