| ||||
Copyright 1999 Sams Publishing |
|
Overriding the run() Method |
After extending Thread , the next step is to override the run() method because the run() method of Thread does nothing: |
public void run() { } |
When a new thread is started, the entry point into the program is the run() method. The first statement in run() will be the first statement executed by the new thread. Every statement that the thread will execute is included in the run() method or is in other methods invoked directly or indirectly by run() . The new thread is considered to be alive from just before run() is called until just after run() returns, at which time the thread dies . After a thread has died, it cannot be restarted. |
In this chapters example, run() is overridden with code to loop for 10 iterations and print the message New thread each time through: |
public void run() { |
for (int i = 0; i < 10; i++) { |
System.out.println(New thread); |
} |
} |
After the for loop completes, the thread returns from the run() method and quietly dies. |
| |||
Toc |