Java之守护线程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82146221

前台线程、守护线程:   前台线程 如果都死光了,则 守护线程会自杀
 
创建一个线程对象,默认与创建环境一致 (ex:主线程是前台线程,那么在主线程创建的线程对象默认是前台线程)
  
void setDaemon(boolean on) : 将该线程标记为守护线程或用户线程。 
注意:setDaemon不能start之后调用

ex:

public class Demo {
	public static void main(String[] args) {
		A a = new A();
		Thread threadA = new Thread(a);
		threadA.setName("AAA ");
		B b = new B();
		Thread threadB = new Thread(b);
		threadB.setName("BBB ");
		
		//启动线程
		threadA.start();
		threadB.setDaemon(true);//把threadB线程设置为后台线程
		threadB.start();

	}
}
/*
 * 测试思路:设计两个线程类,一个充当前台线程,输出10次
 * 					             一个充当守护线程,输出无限次
 * 期望效果:当前台线程输出结束,后台会自动结束
 */
class A implements Runnable{
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().getName()+" : 这是线程  AAA...");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("线程A 结束 ...........");
	}
}

class B implements Runnable{
	@Override
	public void run() {
		while(true){
			System.out.println(Thread.currentThread().getName()+" : 这是线程 BBB...");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

运行结果图:(threadB线程的死循环输出会停止)

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82146221