Thread priorities

Chapter: Thread priorities

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.


Exercise 9

Run Race5.java at least 10 times. How many times does dog 2 win? Now add some print statements so you can see how often each dog gets to execute. An easy way to to do this is to add the print statement to the code for raceFinished().


Exercise 10

Try using the old sleep range of 300-600 milliseconds for both dogs. Does Dog 2 still have much of an advantage. Why or why not?


Exercise 11

if you have time. Add 5 more dogs and set the sleep range back to 3-6 milliseconds. Now arrange a method for an unscrupulous user to "fix" the race. Read the fixer's choice as commandline argument args[0] and then adjust the thread priorities so that the chosen dog is very likely to win. For example, if Tony Soprano types java Race5 4 then you should fix the thread priorities so that dog 4 wins most of the time.


rhyspj@gwu.edu