Pages

Monday, September 24, 2012

Starting Threads


Starting a Thread : 
Thread t = new Thread();
t.start() : 

what happens after you call start()?
The good stuff:
¦ 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.

There’s nothing special about the run() method as far as Java is
concerned. Like main(), it just happens to be the name (and signature) of the method that the new thread knows to invoke. So if you see code that calls the run() method on a Runnable (or even on a Thread instance), that’s perfectly legal. But it doesn’t mean the
run() method will run in a separate thread! Calling a run() method directly just means you’re invoking a method from whatever thread is currently executing, and the run() method goes onto the current call stack rather than at the beginning of a new call stack.

The following code does not start a new thread of execution:
      Thread t = new Thread();
      t.run(); // Legal, but does not start a new thread


Running this code produces the following, extra special, output:
% java NameThread
NameRunnable running
Run by Fred

To get the name of a thread you call—who would have guessed—getName() on the Thread instance. But the target Runnable instance doesn't even have a reference to the Thread instance, so we first invoked the static Thread.currentThread() method, which returns a reference to the currently executing thread, and then we invoked getName() on that returned reference.

No comments:

Post a Comment