Results 1 to 3 of 3

Thread: Java - Daemon Threads

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Ridgefield Park, NJ

    Java - Daemon Threads

    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);

  2. #2
    New Member
    Join Date
    Jun 2008

    Thumbs up Re: Java - Daemon Threads

    First thanks for the program.

    Im new in JAVA, I want to know how to add GUI in this program.

  3. #3
    New Member
    Join Date
    Nov 2009

    Re: Java - Daemon Threads

    Very nice post with a ton of informative information. I really appreciate the fact that you approach these topics from a stand point of knowledge and information
    instead of the typical “I think” mentality that you see so much on the internet these days.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width