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
以上是 Java如何检查线程是否是守护程序线程? 的全部内容, 来源链接: utcz.com/z/321403.html