ForkJoinPool 中的工作线程是 Daemon 线程吗?

问题描述 投票:0回答:3

我正在阅读《Java - 完整参考》一书中有关 Fork/Join 框架的内容。它说 ForkJoinPool 使用守护线程 :


ForkJoinPool 使用守护线程。守护线程是自动的 当所有用户线程都终止时终止。因此,不存在 需要显式关闭 ForkJoinPool。然而,随着 公共池的例外,可以通过调用来做到这一点 关闭( )。 shutdown()方法对公共池没有影响。

这是否意味着所有
    ForkJoinWorkerThread
  1. 都是守护线程?
    既然守护线程是
  2. 低优先级线程
  3. ,那么我们不应该使用ForkJoinPool来执行重要任务吗?
    如果工作线程不是守护线程,那么 
  4. shutdown()
  5. 会等待工作线程完成吗?
    
        
java multithreading concurrency forkjoinpool
3个回答
3
投票
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().awaitQuithesis。

A

:ForkJoinPool 忽略关闭,但应用程序可以调用 awaitQuithesis 来确保所有任务都完成。


2
投票
是的
  1. 不,守护线程的优先级与普通线程的优先级相同。 此外,您可以将它们的优先级设置为所需的级别。 引用的文章只是建议使用守护线程来执行不太重要的任务,因为当 JVM 退出时不能保证它们完成工作。
  2. 是的

0
投票
Javadoc

,“所有工作线程都通过 Thread.isDaemon() 设置为 true 进行初始化”。

    

© www.soinside.com 2019 - 2024. All rights reserved.