Daemon
threads are low priority threads, which are mainly used for
background processing
How
to make a thread Daemon
Syntax
public final void
setDaemon(boolean on)
When
you set the setDaemon to true for a thread, then it acts as a daemon
thread.
How
to know whether a thread is daemon or not
Syntax:
isDaemon()
returns true if this thread is
a daemon thread; false otherwise.
Notable
points
1.
The Java Virtual Machine exits when the only threads running are all
daemon threads.
Example
class MyThread implements Runnable{ public void run(){ while(true){ System.out.println("My Name is " + Thread.currentThread().getName()); } } public static void main(String args[]){ MyThread task1 = new MyThread(); Thread t1 = new Thread(task1); Thread t2 = new Thread(task1); Thread t3 = new Thread(task1); t1.setDaemon(true); t2.setDaemon(true); t3.setDaemon(true); t1.start(); t2.start(); t3.start(); } }
Sample
Output
My Name is Thread-0
Observation
Above
program has 3 threads. All the threads are set to daemon. If the
threads are not set to daemon, then the program will run infinitely.
In the above program all the threads are daemon, So once the main
thread finishes its exection, JVM don't bother about the daemon
threads. It simply quits.
2.
SetDaemon() must be called before the thread is started. If you call
setDaemon() after calling the Thread start method, setDaemon() throws
IllegalThreadStateException.
Example
class MyThread implements Runnable{ public void run(){ try{ System.out.println("I am feeling sleepy"); Thread.currentThread().sleep(5000); System.out.println("Time to work"); } catch(InterruptedException e){ } } public static void main(String args[]){ MyThread task1 = new MyThread(); Thread t1 = new Thread(task1); t1.start(); t1.setDaemon(true); } }
Sample
Output
I am feeling sleepyException in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Unknown Source) at MyThread.main(MyThread.java:22) Time to work
No comments:
Post a Comment