Daemon Threads in Java

Previous
Next

Daemon threads:

  • Thread behavior is either Daemon or Non-Daemon.
  • Daemon threads execute background logic of application.
  • Daemon threads also called service-threads.
  • Daemon threads are invisible threads.
  • Every thread is by default Non daemon.
  • Non daemon threads execute foreground logic of application.
  • Once Non daemon threads execution completed in the application, all daemon threads will be terminated automatically by the JVM.
  • Thread class is providing pre-defined functionality to change the behavior from Non daemon to Daemon.
class Thread
{
	public final void setDaemon(boolean on)
	{
		argument is true - then the thread become Daemon
	}
}

Code program:

class Custom extends Thread
{
	public void run()
	{
		for(int i=1 ; i<=10 ; i++)
		{
			System.out.println("Daemon : " + i);
			try{
				Thread.sleep(1000);
			}catch(Exception e){ }
		}
	}
}
class Default 
{
	public static void main(String[] args) 
	{
		Custom t = new Custom();
		t.setDaemon(true);
		t.start();

		for(int i=1 ; i<=10 ; i++)
		{
			System.out.println("Non-Daemon : " + i);
			try{
				Thread.sleep(300);
			}catch(Exception e){ }
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form