守护线程与其作用

       守护线程是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。在 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...

 

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