Two method related to daemon thread
This method can be used to mark thread as user or daemon thread. If you put setDaemon(true), it makes thread as daemon.
This method can be used to check if thread is daemon or not.
Daemon Thread example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package org.arpit.java2blog; class SimpleThread implements Runnable{ public void run() { if(Thread.currentThread().isDaemon()) System.out.println(Thread.currentThread().getName()+" is daemon thread"); else System.out.println(Thread.currentThread().getName()+" is user thread"); } } public class DaemonThreadMain { public static void main(String[] args){ SimpleThread st=new SimpleThread(); Thread th1=new Thread(st,"Thread 1");//creating threads Thread th2=new Thread(st,"Thread 2"); Thread th3=new Thread(st,"Thread 3"); th2.setDaemon(true);//now th2 is daemon thread th1.start();//starting all threads th2.start(); th3.start(); } } |
Thread 3 is user thread
Thread 2 is daemon thread
Please note that you can not convert user thread to daemon thread once it is started otherwise it will throw IllegalThreadStateException.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.arpit.java2blog; class SimpleThread implements Runnable{ public void run() { if(Thread.currentThread().isDaemon()) System.out.println(Thread.currentThread().getName()+" is daemon thread"); else System.out.println(Thread.currentThread().getName()+" is user thread"); } } public class DaemonThreadMain { public static void main(String[] args){ SimpleThread st=new SimpleThread(); Thread th1=new Thread(st,"Thread 1");//creating threads Thread th2=new Thread(st,"Thread 2"); Thread th3=new Thread(st,"Thread 3"); th1.start();//starting all threads th2.start(); th3.start(); th2.setDaemon(true);//now converting user thread to daemon thread after starting the thread. } } |
Thread 2 is user thread
Thread 3 is user thread
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1388)
at org.arpit.java2blog.DaemonThreadMain.main(DaemonThreadMain.java:28)