java中的daemon thread
java中的daemon thread
java中有兩種類型的thread,user threads 和 daemon threads。
User threads是高優先級的thread,JVM將會等待所有的User Threads運行完畢之后才會結束運行。
daemon threads是低優先級的thread,它的作用是為User Thread提供服務。 因為daemon threads的低優先級,并且僅為user thread提供服務,所以當所有的user thread都結束之后,JVM會自動退出,不管是否還有daemon threads在運行中。
因為這個特性,所以我們通常在daemon threads中處理無限循環的操作,因為這樣不會影響user threads的運行。
daemon threads并不推薦使用在I/O操作中。
但是有些不當的操作也可能導致daemon threads阻塞JVM關閉,比如在daemon thread中調用join()方法。
我們看下怎么創建daemon thread:
public class DaemonThread extends Thread{public void run(){while(true){log.info("Thread A run");try {log.info("Thread A is daemon {}" ,Thread.currentThread().isDaemon());Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) throws InterruptedException {DaemonThread daemonThread = new DaemonThread();daemonThread.setDaemon(true);daemonThread.start();} }創建 daemon thread很簡單,只需要在創建之后,設置其daemon屬性為true即可。
注意setDaemon(true)必須在thread start()之前執行,否則會拋出IllegalThreadStateException
上面的例子將會立刻退出。
如果我們將daemonThread.setDaemon(true);去掉,則因為user thread一直執行,JVM將會一直運行下去,不會退出。
這是在main中運行的情況,如果我們在一個@Test中運行,會發生什么現象呢?
public class DaemonThread extends Thread{public void run(){while(true){log.info("Thread A run");try {log.info("Thread A is daemon {}" ,Thread.currentThread().isDaemon());Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}@Testpublic void testDaemon() throws InterruptedException {DaemonThread daemonThread = new DaemonThread();daemonThread.start();} }我們將main方法改成了@Test執行。執行之后我們會發現,不管是不是daemon thread, Test都會立刻結束。
再看一個daemon線程中啟動一個user thread的情況:
public class DaemonBThread extends Thread{Thread worker = new Thread(()->{while(true){log.info("Thread B run");log.info("Thread B is daemon {}",Thread.currentThread().isDaemon());}});public void run(){log.info("Thread A run");worker.start();}public static void main(String[] args) {DaemonBThread daemonThread = new DaemonBThread();daemonThread.setDaemon(true);daemonThread.start();} }這個例子中,daemonThread啟動了一個user thread,運行之后我們會發現,即使有user thread正在運行,JVM也會立刻結束執行。
本文的例子可以參考https://github.com/ddean2009/learn-java-concurrency/tree/master/DaemonThread
更多精彩內容且看:
- 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
- java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程
更多教程請參考 flydean的博客
總結
以上是生活随笔為你收集整理的java中的daemon thread的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中interrupt,inter
- 下一篇: java中ThreadPool的介绍和使