InterviewSolution
Saved Bookmarks
| 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. Output: t1 is Daemon thread t3 is Daemon thread t2 is User threadBut 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 |
|