javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



Daemon Thread

  • Daemon thread is running in background.
  • It provides services to user thread.
  • Daemon thread is like garbage collector, finalizer etc.
  • It is created automatically by JVM, when a user thread is created.
  • It is automatically terminated when there is no user thread in the system. In other words, JVM terminates Daemon threads automatically when all the user threads die.
  • Daemon thread can be seen using the command Jconsole in the command prompt.
  • The Jconsole tool provides information about the loaded classes, memory usage, running threads etc.
  • Daemon thread is a low priority thread. Daemon thread performs background support task for user thread.

There are two methods

  1. public void setDaemon (boolean status) :- It is used to mark the current thread as either daemon thread or user thread.
  2. public boolean isDaemon() :- It is used to check whether current thread is daemon thread. It returns true if current thread is daemon thread , otherwise it returns false.

Example 1

public class Exp1 extends Thread {
	public void run() {
	if (Thread.currentThread().isDaemon())
	{
		System.out.println(Thread.currentThread().getName()+" Daemon thread is working");
	}
	else
	{
		System.out.println(Thread.currentThread().getName()+ " User Thread is working");
	}
	}
	
	public static void main(String [] args)
	{
		Exp1 t1 = new Exp1 ();
		Exp1 t2 = new Exp1();
		
		t1.setName("t1");
		t2.setName("t2");
		t1.setDaemon(true);
		
		t1.start();
		t2.start();
	}
}

Output

t1 Daemon thread is working
t2 User Thread is working


© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.