简体   繁体   English

为什么将来的.isDone()必须在executorService.shutdown()之后

[英]Why future .isDone() must after the executorService.shutdown()

Why future .isDone() must after the executorService.sutdown() . 为什么将来的.isDone()必须在executorService.sutdown()

This can work: 这可以工作:

Future<Integer> submit1 = executorService.submit(callable);
executorService.shutdown();
while (submit1.isDone()){
   System.out.println(submit1.get());
}

But after I commented this line: 但是在我评论了这一行之后:

Future<Integer> submit1 = executorService.submit(callable);
//executorService.shutdown();
while (submit1.isDone()){
   System.out.println(submit1.get());
}

It can't print any result. 它无法打印任何结果。

You shouldn't be calling submit1.isDone() in the first place, and definitely not in a while loop. 您不应该首先调用submit1.isDone() ,并且绝对不要在while循环中调用。 As Future.get() is a blocking call, you'll get the same behaviour from both when you remove the while() part. 由于Future.get()是一个阻塞调用,因此在删除while()部分时,两者都会得到相同的行为。

The reason you're not getting anything printed in the second case is because the callable hasn't had a chance to finish, so the condition of while is false. 在第二种情况下没有打印任何内容的原因是因为可调用对象没有完成的机会,所以while条件为假。

What you can call after shutdown() is ExecutorService.awaitTermination() . shutdown()之后可以调用的是ExecutorService.awaitTermination() It will wait up to the given amount of time for all tasks to finish. 它将等待给定的时间,以完成所有任务。 If you don't want the tasks to finish, you can call shutdownNow() . 如果您不希望任务完成,则可以调用shutdownNow()

Because when you call .shutdown() thread's state will change which makes isDone return true. 因为当您调用.shutdown()时,线程的状态将改变,这会使isDone返回true。 Look at the ThreadPoolExecutor implementation how it changes your threads state: 查看ThreadPoolExecutor实现,它如何更改线程状态:

public void shutdown() {
    //...
    tryTerminate();
}


/**
 * Transitions to TERMINATED state if either (SHUTDOWN and pool
 * and queue empty) or (STOP and pool empty). 
 * ....
 * ....
 */
final void tryTerminate() {
....
}

And isDone() documentation says that this method returns true due to normal termination, exception or cancellation . isDone()文档说, 由于正常的终止,异常或取消 ,此方法返回true So: 所以:

1) You submitted Callable 1)您提交了Callable

2) You shutDown process, so its state is now TERMINATED 2)您关闭了进程,因此其状态现在为TERMINATED

3) isDone returns true, you see the out. 3) isDone返回true,您看到了。

In other cases, your Callable never terminates, throws an exception or canceled which makes isDone always return false. 在其他情况下,Callable永不终止,引发异常或被取消,这使isDone始终返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM