Jump to content


Thread


  • Please log in to reply
1 reply to this topic

#1 bharath

bharath

    Newbie

  • Members
  • Pip
  • 1 posts

Posted 29 August 2011 - 09:53 AM

Hi friends,i'm beginner to this form,i have a question for all.. In the below code NewThread() is not having any return type,even its not executing in Jcreator.But it was an example in a book and even in net..Can any one explain how it will be???



class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
  
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(500);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}

#2 buddybob

buddybob

    Advanced Member

  • Members
  • PipPipPip
  • 452 posts
  • Gender:Male
  • Location:Bangalore
  • Interests:Java, Airplanes, Trance Music, Movies...blah blah

Posted 04 September 2011 - 01:09 PM

If your question is about how NewThread() which is declared as a method does not have a return type, the answer is that NewThread() happens to be a constructor of the class. Constructors are special methods which are invoked when you create a new instance of the class using the new keyword. Constructors do not specify a return type. They implicitly return an instance of the class they are created in.

P.S. On a side-note, it is not wise to spawn a new thread in the constructor of a class and subsequently start it. Constructors must be lazy, i.e. defer initializing expensive resources to some other method which can be invoked after construction exactly when its needed. The other trouble with your code is that the code which creates a new instance of NewThread will never get access to the the thread that is created and started in the constructor. Please consider avoiding this way of dealing with threads. Threads are expensive resources and can have a lot of side-effects with object state if not handled carefully.

Hope it helps! :smile:
Best Regards,
Ranganath Kini
Sun Certified Java Programmer