簡體   English   中英

ForkJoinPool 中的工作線程是守護線程嗎?

[英]Are worker threads in ForkJoinPool are Daemon threads?

我正在閱讀Java - The Complete Reference一書中有關 Fork/Join Framework 的信息。 它說ForkJoinPool使用守護線程:

ForkJoinPool 使用守護線程。 當所有用戶線程都已終止時,守護程序線程會自動終止。 因此,無需顯式關閉 ForkJoinPool。 但是,除了公共池之外,可以通過調用 shutdown() 來實現。 shutdown() 方法對公共池沒有影響。

  1. 這是否意味着所有ForkJoinWorkerThread都是守護線程?
  2. 既然守護線程是低優先級線程,那么我們不應該將ForkJoinPool用於重要任務嗎?
  3. 如果工作線程不是守護線程,那么shutdown()是否等待工作線程完成?

1.

jshell> ForkJoinPool.commonPool().execute(() ->  System.out.println(Thread.currentThread().getClass() + " isDaemon?  " + Thread.currentThread().isDaemon()))
class java.util.concurrent.ForkJoinWorkerThread isDaemon?  true

jshell>

:是的,它們是守護線程。

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

返回公共池實例。 這個池是靜態構建的; 它的運行 state 不受 shutdown() 或 shutdownNow() 嘗試的影響。 然而,這個池和任何正在進行的處理都會在程序 System.exit(int) 時自動終止。 任何依賴異步任務處理在程序終止之前完成的程序都應該在退出之前調用 commonPool().awaitQuiescence。

A : ForkJoinPool 忽略關閉,但應用程序可以調用awaitQuiescence以確保所有任務都完成。

  1. 是的
  2. 不,守護線程的優先級和普通線程一樣。 此外,您可以將它們的優先級設置為所需的級別。 引用的文章只是建議將守護線程用於不太重要的任務,因為當 JVM 退出時,不能保證它們完成工作。
  3. 是的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM