1.

How can we create daemon threads?

Answer»

We can create DAEMON threads in java using the thread class setDaemon(true). It is used to mark the current thread as daemon thread or USER thread. isDaemon() method is generally used to check whether the current thread is daemon or not. If the thread is a daemon, it will return true otherwise it returns false.  
Example:   
Program to illustrate the use of setDaemon() and isDaemon() method. 

public class DaemonThread extends Thread { public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is Daemon thread"); } else { System.out.println(getName() + " is User thread"); } } public static void main(String[] args) { DaemonThread t1 = NEW DaemonThread("t1"); DaemonThread t2 = new DaemonThread("t2"); DaemonThread t3 = new DaemonThread("t3"); // Setting user thread t1 to Daemon t1.setDaemon(true); // starting first 2 threads t1.START(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); } }

Output:  

t1 is Daemon thread t3 is Daemon thread t2 is User thread

But one can only call the setDaemon() method before start() method otherwise it will definitely throw IllegalThreadStateException as shown below:   

public class DaemonThread extends Thread {  public void run()  {  System.out.println("Thread name: " + Thread.currentThread().getName());  System.out.println("Check if its DaemonThread: " + Thread.currentThread().isDaemon());  }  public static void main(String[] args)  {  DaemonThread t1 = new DaemonThread();  DaemonThread t2 = new DaemonThread();  t1.start(); // Exception as the thread is already STARTED  t1.setDaemon(true);  t2.start();  } } 

Output:  

Thread name: Thread-0 Check if its DaemonThread: false


Discussion

No Comment Found