我正在阅读《Java-完整参考》一书中关于Fork/Join框架的内容。它说ForkJoinPool
使用守护进程线程:
ForkJoinPool使用守护进程线程。守护进程线程自动在所有用户线程都已终止时终止。因此,不存在需要显式关闭ForkJoinPool。然而除了公共池之外,可以通过调用关机((。shutdown((方法对公用池没有影响。
- 这是否意味着所有
ForkJoinWorkerThread
都是守护进程线程 - 既然守护进程线程是低优先级线程,那么我们不应该将
ForkJoinPool
用于重要任务吗 - 如果工作线程不是守护进程线程,那么
shutdown()
是否等待工作线程完成
1.
jshell> ForkJoinPool.commonPool().execute(() -> System.out.println(Thread.currentThread().getClass() + " isDaemon? " + Thread.currentThread().isDaemon()))
class java.util.concurrent.ForkJoinWorkerThread isDaemon? true
jshell>
A:是的,它们是守护进程线程。
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默认情况下创建与任何其他线程具有相同优先级的线程。
3.
来自ForkJoinPool#commonPool 的javadoc
返回公共池实例。此池是静态构建的;其运行状态不受shutdown((或shutdownNow((尝试的影响。然而,此池和任何正在进行的处理都会在程序System.exit(int(时自动终止。任何依赖异步任务处理在程序终止前完成的程序都应该在退出前调用commonPool((.awaitQuience。
A:ForkJoinPool忽略关闭,但应用程序可以调用awaitQuience以确保所有任务都已完成。
- 是
- 不,守护进程线程的优先级与普通线程的优先级相同。此外,您可以将它们的优先级设置为所需级别。引用的文章只是建议将守护进程线程用于不太重要的任务,因为它们不能保证在JVM退出时完成工作
- 是