Java provides a range of priorities for threads:
Priorities range from 1 to 10 (although these numbers may change).
The lowest priority is the constant Thread.MIN_PRIORITY.
The highest priority is Thread.MAX_PRIORITY.
The normal (default) priority is Thread.NORM_PRIORITY.
You can set the priority of a thread using the method setPriority(). As an example, let us set different priorities for the two dogs in the method race(). Here's the source file. Note. Since I first prepared this set of exercises, CPUs have gotten faster and multicore machines are common. The program Race5.java no longer illustrates what higher priorities can do for you. In order to see the effect of setting higher priorities load Race55.java instead. This adds some busy waiting to the nap method in the Dog class. Busy waiting means the thread will waste some real time and there will be actual competition for your computer's resources. Notice the constant BIG that is assigned a value in the Dog class. It controls the amount of busy waiting. As I write (April 2011) a value of 1000 for BIG pretty well guarantees that the highest priority dog (thread) will win the race. A value of 100 does not. Do some experimenting for yourself.
void race () { d1.setPriority(Thread.NORM_PRIORITY); d2.setPriority(Thread.NORM_PRIORITY+3); Dog.startRace(); d1.start(); d2.start(); }
We also decreased the sleep time to the range 3-6 milliseconds:
Dog d1 = new Dog (1, drawingArea, 3, 6, this); Dog d2 = new Dog (2, drawingArea, 3, 6, this);
Of course, that speeds up the race so it's hard to see each dog's progress. Nevertheless when executed, the second dog clearly wins.