Java Daemon Thread


 

Java Daemon Thread

In this segment of tutorial we will learn about the Daemon Thread.Then We will create an example and make the use of Daemon thread.

In this segment of tutorial we will learn about the Daemon Thread.Then We will create an example and make the use of Daemon thread.

  • Daemon thread is the supporting thread.
  • It runs in the background.
  • Daemon thread gets teminated if no non daemons threads are running.
  • Any threads can be set as daemon thread.


Java Daemon Thread Example
public class deamon extends Thread {
	public deamon(String s) {
		super(s);
	}

	@Override
	public void run() {
		System.out.println("entering run()");
		try {
			System.out.println("in run() - currentThread()="
					+ Thread.currentThread());
			for (int x = 1; x <= 3; x++) {

				System.out.println(x + "   this is daemon thread "
						+ Thread.currentThread().isDaemon());
				try {
					Thread.sleep(300);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("thread woke up again");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public static void main(String[] args) {
		deamon d1 = new deamon("1");
		d1.setDaemon(true);
		deamon d2 = new deamon("2");
		deamon d3 = new deamon("3");
		d1.start();
		d2.start();
		d3.start();
	}
}

Output :

entering run() entering run() in run() - currentThread()=Thread[1,5,main] in run() - currentThread()=Thread[3,5,main] 1 this is daemon thread false 1 this is daemon thread true entering run() in run() - currentThread()=Thread[2,5,main] 1 this is daemon thread false thread woke up again 2 this is daemon thread false thread woke up again 2 this is daemon thread true thread woke up again 2 this is daemon thread false thread woke up again 3 this is daemon thread false thread woke up again 3 this is daemon thread true thread woke up again 3 this is daemon thread false thread woke up again thread woke up again thread woke up again

Ads