英文:
Are worker threads in ForkJoinPool are Daemon threads?
问题
- 这是否意味着所有的
ForkJoinWorkerThread
都是守护线程? - 由于守护线程是低优先级线程,那么我们不应该将
ForkJoinPool
用于重要任务吗? - 如果工作线程不是守护线程,那么
shutdown()
方法是否等待工作线程完成?
英文:
I am reading about Fork/Join Framework from book Java - The Complete Reference. It says that ForkJoinPool
uses daemon threads :
> ForkJoinPool uses daemon threads. A daemon thread is automatically
> terminated when all user threads have terminated. Thus, there is no
> need to explicitly shut down a ForkJoinPool. However, with the
> exception of the common pool, it is possible to do so by calling
> shutdown( ). The shutdown( ) method has no effect on the common pool.
- Does this means all
ForkJoinWorkerThread
are daemon threads? - Since daemon threads are low priority threads, then we shouldn't use
ForkJoinPool
for important tasks? - If worker threads are not daemon threads, then does
shutdown()
waits for worker threads to finish?
答案1
得分: 3
1.
A: 是的,它们是守护线程。
2.
A: ForkJoinPool默认创建具有与其他线程相同优先级的线程。
3.
A: ForkJoinPool忽略了shutdown,但应用程序可以调用awaitQuiescence来确保所有任务都已完成。
英文:
1.
jshell> ForkJoinPool.commonPool().execute(() -> System.out.println(Thread.currentThread().getClass() + " isDaemon? " + Thread.currentThread().isDaemon()))
class java.util.concurrent.ForkJoinWorkerThread isDaemon? true
jshell>
A: yes, they are daemon threads.
2.
jshell> new Thread(() -> System.out.println("isDaemon? " + Thread.currentThread().isDaemon() + " priority:" + Thread.currentThread().getPriority())).start()
isDaemon? false priority:5
jshell> ForkJoinPool.commonPool().execute(() -> System.out.println("isDaemon? " + Thread.currentThread().isDaemon() + " priority:" + Thread.currentThread().getPriority()))
isDaemon? true priority:5
A: ForkJoinPool by default creates threads with the same priority as any other thread.
3.
from javadoc of ForkJoinPool#commonPool
> Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts to shutdown() or shutdownNow(). However this pool and any ongoing processing are automatically terminated upon program System.exit(int). Any program that relies on asynchronous task processing to complete before program termination should invoke commonPool().awaitQuiescence, before exit.
A: ForkJoinPool ignores shutdown, but application can call awaitQuiescence to ensure that all task are complete.
答案2
得分: 2
- 是的
- 不,守护线程的优先级与普通线程相同。此外,您可以将它们的优先级设置为所需的级别。所引用的文章只是建议将守护线程用于不太重要的任务,因为它们不能保证在JVM退出时完成工作。
- 是的
英文:
- yes
- no, the priority of daemon thread is the same as that of ordinary threads.
Moreover, you can set their priority to the desired level.
The referenced article just proposes to use daemon threads for less important tasks, as they are not guaranteed to finish their work when JVM exits. - yes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论