Home  >  Article  >  Java  >  What is the importance of isDaemon() method in Java?

What is the importance of isDaemon() method in Java?

WBOY
WBOYforward
2023-08-24 15:29:031107browse

What is the importance of isDaemon() method in Java?

The daemon thread is a low-priority thread in Java. It runs in the background and is usually created by the JVM to perform background tasks, such as garbage collection. (GC). If no user thread is running, the JVM can exit even if the daemon thread is running. The only purpose of a daemon thread is to provide services to user threads. You can use the isDaemon() method to determine whether a thread is a daemon thread. The Chinese translation of

Grammar

Public boolean isDaemon()

Example

is:

Example

class SampleThread implements Runnable {
   public void run() {
      if(Thread.currentThread().isDaemon())
         System.out.println(Thread.currentThread().getName()+" is daemon thread");
      else
         System.out.println(Thread.currentThread().getName()+" is user thread");
   }
}
// Main class
public class DaemonThreadTest {
   public static void main(String[] args){
      SampleThread st = new SampleThread();
      Thread th1 = new Thread(st,"Thread 1");
      Thread th2 = new Thread(st,"Thread 2");
      th2.setDaemon(true); // set the thread th2 to daemon.
      th1.start();
      th2.start();
   }
}

Output

Thread 1 is user thread
Thread 2 is daemon thread

The above is the detailed content of What is the importance of isDaemon() method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete