Java 守护线程的理解

package thread;

public class Thread_Daemon {

	public static void main(String[] args) {
		/**
		 * 后台线程在全部前台线程结束后,后台线程被结束
		 * 
		 * 推论:java进程在全部前台线程结束时候结束。
		 * 如果java进程没有结束的话,则说明存在一个以上的没有结束的前台线程正在运行
		 * 
		 * 
		 * @author 清风已来
		 */
		Thread1 t1 =new Thread1();
		Thread2 t2 =new Thread2();
		Thread3 t3 =new Thread3();
		//将t2线程设置为守护线程
		t2.setDaemon(true);
		//启动线程
		t1.start();
		t2.start();
		t3.start();
	
		

		/*
		Thread t3 =new Thread() {
			public void run() {
				for(int i=0; i<200;i++) {
					System.out.println("前台2:"+i);
					try {
						Thread.sleep(100);
					}catch(InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("前台2ok");
			}
		};*/
		
	}
}

class Thread1 extends Thread{
	public void run() {
		for(int i=0; i<200;i++) {
			System.out.println("前台:"+i);
			try {
				Thread.sleep(100);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("前台ok");
	}
}
class Thread2 extends Thread{
	public void run() {
		for(int i=0; i<500;i++) {
			System.out.println("后台:"+i);
			try {
				Thread.sleep(100);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("后台ok");
	}
}
class Thread3 extends Thread{
	public void run() {
		for(int i=0; i<100;i++) {
			System.out.println("前台2:"+i);
			try {
				Thread.sleep(100);
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("前台2ok");
	}
}

  

原文地址:https://www.cnblogs.com/xyk1987/p/8266998.html