简体   繁体   English

从不同于创建ExecutorService的线程中调用ExecutorService.shutdown()和awaitTermination()是否安全?

[英]Is it safe to call ExecutorService.shutdown() and awaitTermination() from a different thread than created the ExecutorService?

I create the ExecutorService on Thread A, then Thread B calls shutdown() and awaitTermination() on the ExecutorService. 我在线程A上创建ExecutorService,然后线程B在ExecutorService上调用shutdown()awaitTermination()

Assuming all tasks have been already been submitted prior to Thread B's creation, and no new tasks will be submitted, is there any danger? 假设在创建线程B之前已经提交了所有任务,并且不会提交任何新任务,是否有危险?

I'm guessing it's fine, but it never hurts to ask. 我猜很好,但是问它从来没有伤害。

As you guessed it is absolutely fine to call ExecutorService shutdown() and awaitTermination(..) on the ExecutorService from Thread B. 如您所料,从线程B调用ExecutorService上的ExecutorService shutdown()和awaitTermination(..)是绝对好的。

Infact in the usual usage of ExecutorService, one thread takes care of adding all the thread tasks to the executorservice and then the same thread initiates a graceful shutdown() and then awaitTermination(..). 实际上,在通常使用ExecutorService的情况下,一个线程负责将所有线程任务添加到executorservice中,然后同一线程启动正常的shutdown(),然后启动awaitTermination(..)。 So in your case you are just creating ThreadB to do your shutdown tasks. 因此,在您的情况下,您只是创建ThreadB来执行关闭任务。

Ideally it would be better to not submit your ThreadB to the same ExecutorService which it would try to shutdown() which I believe you would have taken into consideration. 理想情况下,最好不要将您的ThreadB提交到相同的ExecutorService,否则它将尝试使用shutdown(),我相信您会考虑到这一点。

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

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