How can I create a daemon thread?

Brandon Rohlfs

The Thread API allows Threads to be created which are at the mercy of their user threads. This is accomplished simply by passing true to the setDaemon() method and invoking the method off an instance of the thread wishing to set it's status.

public void setDeamon(boolean b)
The following is a simple program which creates a thread within the context of the main thread of execution. Since the main thread is a user thread the created thread will also be a user thread unless it's status is set otherwise. A couple of notes about the following code. If the created threads status is not set or false is passed to the setDameon() method then the created thread will fully execute. This is because the main thread cannot return until all non-daemon threads are finished. Setting the status to true in our case doesn't give our daemon thread much time to do it's bussiness since the main method will quickly execute then return thus stopping our daemon thread dead in it's tracks. We would be lucky to get a print out of one year!. So what can we do? Either we can put the main thread to sleep for an amount of time (enough to give our dameon thread time to do it's business) or simply make it a non-daemon thread by setting it's status to false.

public class UserThread{ 
 public static void main(String[] args){
  Thread t = new Thread(new DaemonThread(525.00f, 0.09f));
  Thread.sleep(250); // must give the deamon thread a chance to run! 
  }catch(InterruptedException ei){ // 250 mills might not be enough!

class DaemonThread implements Runnable{
 private float principal;
 private float futureval;
 private float rate; 
 private float i;   
 public DaemonThread(float principal, float rate){
  this.principal= principal;
  this.rate = rate;  

 public void run(){ 
  for(int year = 0; year <= 75; year++){
  i = (1 + rate); 
  futureval = principal * (float)Math.pow(i,year); 
  System.out.print(principal + " compounded after " + year + " years @ " + rate + "% = " + futureval);
About | Sitemap | Contact