setDaemon
public final void setDaemon(boolean on)
将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。
该方法必须在启动线程前调用。
public class Test {
public static void main(String[] args) {
// 这个线程在主线程结束后将结束.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int i = 1;
while (true) {
System.out.println("in run ... " + ": No." + (i++));
}
}
});
// 设置为守护线程,注释掉这句就变成死循环了.
thread.setDaemon(true);
// start thread.
thread.start();
// main thread sleep.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
转载请注明原文地址: https://ibbs.8miu.com/read-2263179.html