Daemon thread in java

Daemon thread:

Daemon threads are low priority threads which are act as a service provider for user threads. Life of a daemon thread is depends upon the user threads. JVM automatically terminates daemon thread when all user threads are died. Daemon threads are used for background supporting tasks.

Methods used for daemon threads:

1. public final void setDaemon(boolean on)

Marks this thread as daemon thread if on is true.

2. public final boolean isDaemon()

Returns true if thread is daemon.

Example:

DaemonThreadExample1.java

/**
 * This program is used to show daemon thread example.
 * @author w3spoint
 */
class Test extends Thread{
	public void run(){
	    System.out.println(Thread.currentThread().getName() + " " 
			+ Thread.currentThread().isDaemon());
	}
}
 
public class DaemonThreadExample1 {
	public static void main(String args[]){
		//creating thread.
		Test thrd1 = new Test();
		Test thrd2 = new Test();
 
		//set names
		thrd1.setName("My Thread1");
		thrd2.setName("My Thread2");
 
		//set thrd1 as daemon thread.
		thrd1.setDaemon(true);
 
		//start threads.
		thrd1.start();
		thrd2.start();
	}
}

Output:

My Thread1 true
My Thread2 false

Download this example.

Example: After starting a thread it can’t be set as daemon thread.

DaemonThreadExample2.java

/**
 * This program is used to show that after starting a thread
 * it can't be set as daemon thread.
 * @author w3spoint
 */
class Test extends Thread{
	public void run(){
	  System.out.println(Thread.currentThread().getName() + " " 
			+ Thread.currentThread().isDaemon());
	}
}
 
public class DaemonThreadExample2 {
	public static void main(String args[]){
		//creating thread.
		Test thrd1 = new Test();
		Test thrd2 = new Test();
 
		//set names
		thrd1.setName("My Thread1");
		thrd2.setName("My Thread2");
 
		//start thrd1.
		thrd1.start();
 
		//set thrd1 as daemon thread.
		//java.lang.IllegalThreadStateException here.
		thrd1.setDaemon(true);
 
		//start thread2.
		thrd2.start();
	}
}

Output:

Exception in thread "main" My Thread1 false
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at com.w3spoint.business.DaemonThreadExample2.main
(DaemonThreadExample2.java:30)

Download this example.
 
Next Topic: Can we start a thread twice?
Previous Topic: Joining a thread in java with example.

Content Protection by DMCA.com
Please Share