守護線程與其作用

       守護線程是運行在後臺的一種特殊進程。它獨立於控制終端並且週期性地執行某種任務或等待處理某些發生的事件。在 Java 中垃圾回收線程就是特殊的守護線程。

       當JVM中沒有任何User線程時(非守護線程,JVM則關閉)

用戶線程和守護線程幾乎一樣,唯一的不同之處就在於如果用戶線程已經全部退出運行,只剩下守護線程存在了,JVM也就退出了。  因爲當所有非守護線程結束時,沒有了被守護者,守護線程也就沒有工作可做了,也就沒有繼續運行程序的必要了,程序也就終止了,同時會“殺死”所有守護線程。 也就是說,只要有任何非守護線程還在運行,程序就不會終止。

(1)模擬User線程沒有完全銷燬,程序不會結束

package cn.edu.bjfu.main;

public class ThreadTest {

	public static void main(String[] args) throws Exception{
		//new一個非守護線程
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("Thread is running...");
				}
			}
		});
		//啓動線程
		thread.start();
		Thread.sleep(5000);
		
		//main線程的結束
		System.out.println("main method end...");
	}
	
}

此時打印的結果爲:

Thread is running...
Thread is running...
Thread is running...
Thread is running...
main method end...
Thread is running...
Thread is running...
Thread is running...
Thread is running...


...................

(2)模擬設置爲線程爲守護線程,當沒有User線程時,程序會銷燬

package cn.edu.bjfu.main;

public class ThreadTest {

	public static void main(String[] args) throws Exception{
		//new一個非守護線程
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				while(true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("Thread is running...");
				}
			}
		});
		
		//設置爲守護線程
		thread.setDaemon(true);
		
		//啓動線程
		thread.start();
		Thread.sleep(5000);
		
		//main線程的結束
		System.out.println("main method end...");
	}
	
}

此時,當5s之後,線程會自動銷燬,因爲只有守護線程,沒有非守護線程

Thread is running...
Thread is running...
Thread is running...
Thread is running...
main method end...
Thread is running...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章