Java Reference
In-Depth Information
Implementing Runnable
After all this discussion about threads, we are now ready to finally write one.
I will start by creating a thread using a class that implements the Runnable
interface. The following DisplayMessage class implements Runnable and uses
a while loop to continually display a greeting:
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}
Objects of type DisplayMessage are also of type Runnable because the
DisplayMessage class implements the Runnable interface. However,
DisplayMessage objects are not threads. For example, the following two state-
ments are valid, but be careful about what their result is:
DisplayMessage r = new DisplayMessage (“Hello, World”);
r.run();
The run() method is invoked, but not in a new thread. The infinite while
loop will print “Hello, World” in the current thread that these two statements
appear in. To run DisplayMessage in a separate thread, you need to instantiate
and start a new object of type java.lang.Thread.
The purpose of the Runnable class is to separate the Thread object from
the task it is performing. When you write a class that implements
Runnable, there are two objects involved in the thread: the Runnable
object and the Thread object. The Runnable object contains the code that
executes when the thread finally gets to run. It is the Thread object that is
born, has a priority, starts, is scheduled, runs, blocks, and eventually dies.
When the Thread object is actually running, the run() method of the
Runnable object is the code that executes.
Search WWH ::




Custom Search