Threads and Concurrent Programming
14.3 From the Java Library: java.
The setPriority(int) method lets you set a thread’s priority to an integer value between Thread.MIN PRIORITY and Thread.MAX PRIORITY, the bounds defined as constants in the Thread class. Using setPriority() gives you some control over a thread’s execution. In general, higher-priority threads get to run before, and longer than, lowerpriority threads.
To see how setPriority() works, suppose we change NumberThread’s
constructor to the following:
In this case, each thread sets its priority to its ID number. So, thread five
will have priority five, a higher priority than all the other threads. Suppose we now run 2 million iterations of each of these threads. Because 2
million iterations will take a long time if we print the thread’s ID on each
iteration, let’s modify the run() method, so that the ID is printed every 1
Given this modification, we get the following output when we run
It appears from this output that the threads ran to completion in priority
order. Thus, thread five completed 2 million iterations before thread four
started to run, and so on. This shows that, on my system at least, the Java
Virtual Machine (JVM) supports priority scheduling.