Java Reference
In-Depth Information
Other blocked states. A thread can become blocked for other reasons
besides synchronization. For example, a thread can invoke the wait()
method on an object, which blocks the thread until notify() is invoked on
the same object. A thread can sleep for a certain number of milliseconds,
or a thread can call the join() method and wait for another thread to fin-
ish. As is always the case, when a thread is no longer blocked and
becomes runnable again, the thread is placed in its corresponding prior-
ity queue and gets to run again when the thread scheduler schedules it.
Dead. A thread that runs to completion is referred to as a dead thread.
The term dead is used because it cannot be started again. If you need to
repeat the task of the thread, you need to instantiate a new thread object.
Now that you have seen how threads behave, I will show you the various
ways to write a thread in Java.
Creating a Thread
There are three common ways to write a thread in Java:
You can write a class that implements the Runnable interface, then asso-
ciate an instance of your class with a java.lang.Thread object.
■■
You can write a class that extends the Thread class.
■■
You can write a class that extends the java.util.TimerTask class, and
then schedule an instance of your class with a java.util.Timer object.
■■
I want to point out that although each of these techniques is different, all
three involve implementing the Runnable interface. Either you write a class
that implements Runnable, or you extend a class that already implements
Runnable. (Both the Thread and TimerTask classes implement Runnable.) In
either case, you define the one method in Runnable:
public void run()
The body of the run() method is the path of execution for your thread. When
the thread starts running, the run() method is invoked, and the thread
becomes dead when the run() method runs to completion.
Each of these various ways to create a thread has its advantages and disad-
vantages, but they are mostly design issues. Therefore, whichever technique
you choose will likely be based on your own design and personal preferences.
I will now discuss each of these three techniques, throwing in some important
information about threads along the way.
Search WWH ::




Custom Search