Thursday, November 23, 2006

Creating a Thread

When a thread is created, it must be permanently bound to an object with a run() method. When the thread is started, it will invoke the object's run() method.

There are two ways to create a thread.

The first is to declare a class that extends Thread. When the class is instantiated, the thread and object are created together and the object is automatically bound to the thread. By calling the object's start() method, the thread is started and immediately calls the object's run() method. Here is some code to demonstrate this method.
    // This class extends Thread
class BasicThread1 extends Thread {
// This method is called when the thread runs
public void run() {
}
}
    // Create and start the thread
Thread thread = new BasicThread1();
thread.start();

The second way is to create the thread and supply it an object with a run() method.
This object will be permanently associated with the thread. The object's run() method will be invoked when the thread is started.
This method of thread creation is useful if you want many threads sharing an object.
Here is an example that creates a Runnable object and then creates a thread with the object.

    class BasicThread2 implements Runnable {
// This method is called when the thread runs
public void run() {
}
}
    // Create the object with the run() method
Runnable runnable = new BasicThread2();

// Create the thread supplying it with the runnable object
Thread thread = new Thread(runnable);

// Start the thread


thread.start();

No comments: