You can test if a thread is a daemon thread or a user thread by calling the isDaemon()
method of the Thread
class. If it returns true
then the thread is a daemon thread, otherwise it is a user thread.
package org.kodejava.lang;
public class ThreadCheckDaemon implements Runnable {
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());
}
}
public void run() {
System.out.println("Running [" +
Thread.currentThread().getName() + "]");
}
}
The code snippet print the following output:
FirstThread is a daemon thread.
SecondThread is a user thread
Running [FirstThread]
Running [SecondThread]
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024