Saturday, July 26, 2014

Thread Class

Let’s understand what we are doing here, we have four constructors of Thread class,
  • Thread()
  • Thread(Runnable target)
  • Thread(Runnable target, String name)
  • Thread(String name)
If you create a thread using the no-arg constructor, the thread will call its own run() method when it's time to start working. That's exactly what you want when you extend Thread, but when you use Runnable, you need to tell the new thread to use your run()method rather than its own. The Runnable you pass to the Thread constructor is called the target or the target Runnable.

As you can see in Thread class provided by java, the run() method is define as,
public void run() {
    if (target != null) {
           target.run();// That call your class run() method
    }    
}
At this point, all we have is the plain old java object of Thread class, It is not yet a thread of execution. To get an actual thread—a new call stack—we still have to start the thread.
To start a thread we write ,

t.start();

Few points to remember:
  • When a thread has been instantiated but not started (in other words, the start() method has not been invoked on the Thread instance), the thread is said to be in the new state.
  •  At this stage, the thread is not yet considered to be alive.
  •  Once the start() method is called, the thread is considered to be alive(even though the run() method may not have actually started executing yet).
  •  A thread is considered dead (no longer alive) after the run() method completes.
  •  When start() method called , a new thread of execution starts (with a new call stack).
  • The thread moves from the new state to the runnable state.
  • When the thread gets a chance to execute, its target run() method will run.

No comments :

Post a Comment