简体   繁体   中英

java - Thread.join() for ThreadPoolExecutor

Is there a join()-like method for threads that have been executed through the ThreadPoolExecutor?

If I submit a few Callables to the executor instead and use the get() method on the Futures that they return, will I get similar behavior to a Thread.join()?

They are similar in the sense they both Thread#join() and Future#get() will block until the thread/cllable is finished. In the Thread#join() case, the call returns when the thread dies. No result is returned. In the Future#get() case, it will return when the callable is finished executing its task, but the executing thread will not die (it's usually part of a thread pool, so it will make itself available back to the pool).

If these tasks that you submit to the ExecuterService are mission-critical, it is good practice to add a shutdown hook to your application that calls threadPool.shutdown() to allow for a graceful completion of all running threads, and waits for threadPool.isTerminated() to become true, or waits for threadPool.awaitTermination(max time before force shutdown) to return.

If by "similar", you mean that your current thread will block until the work is done, then yes. The difference is that Thread.join() blocks until the thread in question dies. Future.get() only blocks until the Callable or Runnable that you submitted finishes executing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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