Java Reference
In-Depth Information
Yielding Threads (continued)
Notice that calls to sleep() require the exception to be handled or declared. Figure 15.4
shows the difference that occurred between using yield() and using sleep().
Figure 15.4
The player3 thread gave up the CPU to the lower-priority threads player1
and player2.
Notice that each thread took turns guessing, even though player3 has a higher priority.
Sleeping allowed the three threads to share the CPU more consistently, but it also took
away from the fact that thread3 has a higher priority. If I give player3 a high priority, it makes
sense that player3 should get more CPU time than player1 or player2. In that case,
because sleep() negated the higher priority that was assigned to player3, I would say it is
a better design to use the yield() method, which allowed the higher-priority thread to run
and threads of the same priority to share the CPU among themselves.
Methods of the Thread Class
Now, let's look at the Thread class in more detail. The Thread class has many
useful methods for determining and changing information about a thread,
including:
public void start(). Starts the thread in a separate path of execution, then
invokes the run() method on this Thread object.
public void run(). If this Thread object was instantiated using a separate
Runnable target, the run() method is invoked on that Runnable object. If
you write a class that extends Thread, the overridden run() method in
the child class is invoked.
public final void setName(String name). Changes the name of the
Thread object. There is also a getName() method for retrieving the name.
Search WWH ::




Custom Search