setDaemon():设置一个线程为守护线程(用户线程),当程序中没有非守护线程时,程序结束。
public class ThreadDemo2 {
public static void main(String[] args) {
DaemonThread dt = new DaemonThread();
dt.setDaemon(true);
System.out.println(dt.isDaemon());
dt.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("MainThread-->" + i);
}
}
}
class DaemonThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Daemon-->" + i);
}
}
}
|
|