Recently I was asked a question:
We\'ve got the
setPriority()
method to set a thread for low priority. Then why do we need a daemon thr
An example of
ALSO, shows that thread created by a daemon thread automatically becomes a daemon thread
package junk.daemon_thread_example;
class DeamonThreadPlus implements Runnable{
String id;
boolean createChild;
public DeamonThreadPlus(String id, boolean createChild){
this.id = id;
this.createChild = createChild;
}
@Override
public void run() {
// Parent daemon thread creates child daemon thread by default
if (createChild)
new Thread(new DeamonThreadPlus("DaemonChild", false)).start();
// This thread never self-completes (only terminates when process dies)
while (true){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Daemon "
+ Thread.currentThread().isDaemon()
+ " id = " + id);
}
}
}
class UThread implements Runnable{
@Override
public void run() {
System.out.println("User thread start");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("User thread end (program exits)");
}
}
public class Caller{
public static void main(String[] args) {
Thread dt = new Thread( new DeamonThreadPlus("Daemon", true));
dt.setDaemon(true);
dt.start();
Thread ut = new Thread(new UThread());
ut.setPriority(Thread.MIN_PRIORITY);
ut.start();
}
}
The output is:
User thread start
Daemon true id = Daemon
Daemon true id = DaemonChild
Daemon true id = Daemon
Daemon true id = DaemonChild
Daemon true id = Daemon
Daemon true id = DaemonChild
Daemon true id = Daemon
Daemon true id = DaemonChild
User thread end (program exits)
Daemon true id = DaemonChild
Daemon true id = Daemon