Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Thread Daemon Threads

Related Tutorials


 
 

Share on Google+Share on Google+

Daemon Threads

Advertisement
This section describe about daemon thread in java. Any thread can be a daemon thread.

Daemon Threads

This section describe about daemon thread in java. Any thread can be a daemon thread. Daemon thread are service provider for other thread running in same process, these threads are created by JVM for background task. Any thread created by main thread that run the main method is by default user thread because it inherit the daemon nature from its parent thread from which it is created. Any thread which is created by user thread is user or non daemon thread only, until setDaemon(true) method is true. Thread.setDaemon(true) will create a daemon thread but it can be called only before thread is started or it will throw IllegalThreadStateException if thread is already started and running. The java.lang.Thread class provide two method for daemon thread as follows :

  • public void setDaemon(boolean value) - used to make the user thread as daemon thread.
  • public boolean isDaemon() -  To check whether the thread is daemon thread or not.

Main purpose of daemon thread is to provide services for background task of  user thread if there is not any user thread then JVM will terminate the daemon thread.

Example : A code for creating Daemon Thread

public class DaemonThread  extends Thread
   {
  public void run()
  {
	System.out.println(Thread.currentThread().getName());
	System.out.println(Thread.currentThread().isDaemon());
   }
   
   public static void main(String args[])
   {
	   DaemonThread ob1=new DaemonThread ();
	   DaemonThread ob2=new DaemonThread ();
	   ob1.setDaemon(true);
	   ob1.start();
       ob2.start();
       //ob2.setDaemon(true);// Not allowed it will throw an exception.
     }         
   }

If a user thread is set true to setDaemon() method for creating daemon thread, then it will only allow before thread is started or else it will result an error.

Output : After compiling and executing the above program

Download SourceCode

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 22, 2013

Related Tutorials

Discuss: Daemon Threads  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com