Java如何检查线程是否是守护程序线程?
您可以通过调用Thread类的isDaemon()方法来测试线程是守护程序线程还是用户线程。如果返回true,则该线程为守护程序线程,否则为用户线程。
package org.nhooo.example.lang;
public class ThreadCheckDaemon implements Runnable {
public void run() {
System.out.println("Running [" +
Thread.currentThread().getName() + "]");
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadCheckDaemon(), "FirstThread");
Thread t2 = new Thread(new ThreadCheckDaemon(), "SecondThread");
t1.setDaemon(true);
t1.start();
t2.start();
if (t1.isDaemon()) {
System.out.format("%s is a daemon thread.%n", t1.getName());
} else {
System.out.format("%s is a user thread.%n", t1.getName());
}
if (t2.isDaemon()) {
System.out.format("%s is a daemon thread %n", t2.getName());
} else {
System.out.format("%s is a user thread %n", t2.getName());
}
}
}该代码段显示以下输出:
Running [SecondThread] Running [FirstThread] FirstThread is a daemon thread. SecondThread is a user thread
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短