什么是守护线程
a. 在客户/服务器模式下,服务器的作用是等待用户发来请求,并按请求完成客户的工作
b. 守护线程是为其它线程提供服务的线程,如定时器线程
c. 守护线程一般应该是一个独立的线程,它的run()方法是一个无限循环
d. 守护线程与其它线程的区别是:如果守护线程是唯一运行着的线程,程序会自动退出
e. 把线程变成一个守护线程:r.setDeamon(true);
实例1:
package com.bijian.thread;
import static java.util.concurrent.TimeUnit.*;
public class DaemonTest {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
public void run() {
for (int time = 10; time > 0; --time) {
System.out.println("Time #" + time);
try {
SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.setDaemon(true); // try to set this to "false" and see what happens
t.start();
System.out.println("Main thread waiting...");
SECONDS.sleep(6);
System.out.println("Main thread exited.");
}
}
运行结果:
Main thread waiting... Time #10 Time #9 Time #8 Main thread exited. Time #7
将 t.setDaemon( true ); 语句改为 t.setDaemon( false ); 运行结果如下:
Main thread waiting... Time #10 Time #9 Time #8 Main thread exited. Time #7 Time #6 Time #5 Time #4 Time #3 Time #2 Time #1
实例2:
package com.bijian.thread;
public class MyThread extends Thread {
public void run() {
System.out.println("Daemon is " + isDaemon());
while (true) {
;
}
}
}
package com.bijian.thread;
public class UserDaemonThreadDemo {
public static void main(String[] args) {
if (args.length == 0)
new MyThread().start();
else {
MyThread mt = new MyThread();
mt.setDaemon(true);
mt.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
如果不设置参数,即 args. length == 0 ,运行结果如下:
Daemon is false
且程序一直运行
如果随便设置一个参数,即args.length != 0,设置过程如下
运行结果如下:
Daemon is true
且程序 1 秒后退出