Java Reference
In-Depth Information
Thread player2 = new GuessANumber2(85);
Thread player3 = new GuessANumber2(85);
player3.setPriority(Thread.MAX_PRIORITY);
player1.start();
player2.start();
player3.start();
}
}
Notice in the YieldDemo program that player3 has the maximum priority of a Thread,
which is 10. After each guess, each thread invokes the yield() method. However, because
player3 has a higher priority, it does not yield to player1 or player2. Figure 15.3 shows a
sample output of running the YieldDemo program.
Figure 15.3
The player3 thread gets to guess until it is correct.
The player3 thread hogs the CPU until it is finished executing. After the player3 thread
is done, player1 and player2 politely take turns guessing numbers because each one calls
yield() after each guess. The output of YieldDemo will be similar on any platform, whether
or not time slicing is used.
If you want player3 to actually give up the CPU for lower-priority threads, player3 can
sleep for a short amount of time. You use the sleep() method in the Thread class to cause
the currently running thread to sleep:
public static void sleep(int millisec) throws InterruptedException
I was curious to see what effect sleep() would have on the GuessANumber2 class, so I
took out the call to Thread.yield() and replaced it with the following:
try
{
Thread.sleep(1);
}catch(InterruptedException e)
{}
continued
Search WWH ::




Custom Search