There is a Thread class in the java.lang package. To write
code that will be executed as a separate thread, there are two
possibilities. Either
- Extend Thread in your class and override the
void run() method with the code you wish the thread to run.
- Or write a class which implements the Runnable
interface, which requires the class to have a void run()
method. Then to generate a thread, an instance of the class
implementing Runnable is passed as an argument in the
constructor for a new Thread eg
class Bar implements Runnable {
...
public void run() {
// do what you want
}
...
}
...
Thread foo = new Thread(new Bar());
foo.start();
...
The second approach is the preferred way. Why?
Having created the thread, call void start() on the thread
object to hand the thread into the VM scheduler, which then invokes
the run method.
Ian Wakeman
2005-02-22