Java Reference
In-Depth Information
Although it is easier to extend Thread, there are certain times when you
may not have that option. Keep in mind that you get only one parent class
in Java. If you write a class that already extends a class, extending Thread
is not an option. For example, suppose that you write an applet named
MyApplet. Because the MyApplet class must extend java.applet.Applet,
extending Thread is not an option. To make MyApplet a thread, it must
implement Runnable:
public class MyApplet extends Applet implements Runnable
It is my opinion that implementing Runnable is a better choice in regard
to object-oriented design. The purpose of extending a class is to add
functionality to it. The GuessANumber example extends Thread, but adds
no functionality to the Thread class. From an object-oriented point of
view, GuessANumber is not a Thread (even though it runs in a thread) and
therefore does not satisfy the is a relationship.
That being said, I see developers extend Thread all the time. In fact, in
many of the examples in this chapter, I will extend Thread instead of
implementing Runnable just because it saves me a step. However, when I
do “real” Java development, my threads will be classes that implement
Runnable.
Yielding Threads
Notice in the output of the ThreadDemo in Figure 15.2 (created on Windows XP) that each
thread gets about 5-10 guesses before its time slice runs out. If this program were to run
on a non-time-slicing platform, one thread would likely get a lot of guesses, while the other
thread waited to get scheduled. Of course, there are many indeterminate factors involved
in scheduling the threads, so the output of the program is different each time it runs.
Because the program runs differently each time, the design of the program should not
depend on whether the platform time-slices or not.
If we want this game to be fairer, with each thread getting a chance to guess a number
without waiting too long for the other threads playing, we can design the threads to yield to
one another. A thread yields by invoking the yield() method in the Thread class, which
looks like this:
public static void yield()
This method causes the currently running thread to pause so that other threads can
have a chance to execute. Yielding is a good programming design with threads, but note
that it is only a moderately polite thing for a thread to do because it will yield only to other
threads of the same priority.
continued
Search WWH ::




Custom Search