Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-08-24 15:29:03
forward
1102 people have browsed it

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()
Copy after login

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();
   }
}
Copy after login

Output

Thread 1 is user thread
Thread 2 is daemon thread
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template