Java Reference
In-Depth Information
Yielding Threads (continued)
For example, suppose that you have two threads currently runnable: A of priority 5 and B
of priority 10. If B calls yield(), the A thread does not get a chance to run. In fact, the B
thread does not even leave the CPU. It just keeps on running. However, if A and B are of
the same priority and B calls yield(), B will go to the back of the priority queue and A will
get a chance to run.
The following GuessANumber2 class modifies the GuessANumber class by adding a call
to yield in the run() method:
public class GuessANumber2 extends Thread
{
private int number;
public GuessANumber2(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
Thread.yield();
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ “ guesses “ + guess);
counter++;
}while(guess != number);
System.out.println(“** Correct! “ + this.getName()
+ “ in “ + counter + “ guesses.**”);
}
}
Study the following YieldDemo program and try to determine what happens when the
three threads are started:
public class YieldDemo
{
public static void main(String [] args)
{
System.out.println(“Pick a number between 1 and 100...”);
Thread player1 = new GuessANumber2(85);
Search WWH ::




Custom Search