Java 多线程例子2 前台线程(用户线程) 后台线程(守护线程 ) setDaemon

1,setDaemon(true)后就是后台线程(守护线程 ),反之就是前台线程(用户线程)

2,后台线程 和 前台线程的区别:在java程序中如果所以的前台线程都已经退出,所有的后台线程自动退出。

TestThread为后台线程:

public class ThreadDemo {
	public static void main(String[] args) {
		Thread t = new TestThread();
		t.setDaemon(true);
		t.start();
//		while(true) {
//			System.out.println("main(): "+Thread.currentThread().getName() + " is running");
//		}
	}
}

class TestThread extends Thread {
	public void run() {
		while(true) {
			System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");
		}
	}
}

 运行当前台线程main退出后自动退出。

TestThread和main一样也是前台线程:

public class ThreadDemo {
	public static void main(String[] args) {
		Thread t = new TestThread();
//		t.setDaemon(true);
		t.start();
//		while(true) {
//			System.out.println("main(): "+Thread.currentThread().getName() + " is running");
//		}
	}
}

class TestThread extends Thread {
	public void run() {
		while(true) {
			System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");
		}
	}
}

 

TestThread 就不会退出。

也就是说,所有的前台线程结束后,所有的后台线程会自动退出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值