In this section we are going to describe setDaemon() method with example in java thread.
In this section we are going to describe setDaemon() method with example in java thread.In this section we are going to describe setDaemon() 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 void setDaemon(boolean on) : This
method sets user thread either daemon thread or not by providing value true or
false.
It tells the JVM to make the thread a daemon thread.
Example : In this example we are setting thread 1 as daemon thread.
public class ThreadSetDaemon implements Runnable { public void run() { System.out.println("Thread name : " + Thread.currentThread().getName()); } public static void main(String[] args) throws Throwable { /* Create a thread as a daemon thread */ Thread thread1 = new Thread(new ThreadSetDaemon()); //thread1.setDaemon(true); thread1.start(); System.out.println("Thread is set as daemon thread."); Thread thread2 = new Thread(new ThreadSetDaemon()); thread2.start(); System.out.println("Active threads = " + Thread.activeCount()); thread1.join(); thread2.join(); System.out.println("Thread name : " + Thread.currentThread().getName()); } }
Output :
Thread is set as daemon thread. Active threads = 3 Thread name : Thread-0 Thread name : Thread-1 Thread name : main