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 爱生日祝福语简短独特