Java Thread : isDaemon() method


 

Java Thread : isDaemon() method

In this section we are going to describe isDaemon() method with example in java thread.

In this section we are going to describe isDaemon() method with example in java thread.

Java Thread : isDaemon() method

In this section we are going to describe isDaemon() method with example in java thread.

Daemon Thread  :

In Java Thread, daemon threads are used to perform services for user threads. You can say it they are like service providers for other threads.
It runs in background and most of time created by JVM, performing background tasks.
For example garbage collector thread, screen updater thread, clock handler thread etc.

public final boolean isDaemon() : This method returns boolean value and checks whether given thread is daemon thread or not.

Example :  In this example we are testing threads for daemon thread.

public class ThreadIsDaemon implements Runnable {

    public void run() {
        Thread thread = Thread.currentThread();
        /* Check thread is daemon */
        System.out.println(thread.getName() + " is a daemon thread? " + thread.isDaemon());
  }

    public static void main(String args[]) throws Exception {
        Thread thread1 = new Thread(new ThreadIsDaemon());
        Thread thread2 = new Thread(new ThreadIsDaemon());
        thread1.start();
        thread1.join();
       /* Set thread2 daemon thread */
        thread2.setDaemon(true);
        
        /* Check thread2 is daemon */
        System.out.println(thread2.getName() + " is a daemon thread? " + thread2.isDaemon());
    }
}

Output :

Thread-0 is a daemon thread? false
Thread-1 is a daemon thread? true

Ads