Not all threads are created equal. Sometimes you want to give one thread more time than another. Threads that interact with the user should get very high priorities. Threads that calculate in the background should get low priorities.
Thread priorities are defined as integers between 1 and 10. Ten is the highest priority. One is the lowest. The normal priority is five. Higher priority threads get more CPU time.
Warning: This is exactly opposite to the normal UNIX way of prioritizing processes where the higher the priority number of a process, the less CPU time the process gets.
For your convenience java.lang.Thread
defines three
mnemonic constants, Thread.MAX_PRIORITY
,
Thread.MIN_PRIORITY
and Thread.NORM_PRIORITY
which you can use in place of the numeric values.
You set a thread's priority with the setPriority(int
priority)
method. The following program sets Chris's
priority higher than Mary's whose priority is higher than Frank's.
It is therefore likely that even though Chris starts last and Frank
starts first, Chris will finish before Mary who will finish before
Frank.
public class MixedPriorityTest {
public static void main(String[] args) {
NamedBytePrinter frank = new NamedBytePrinter("Frank");
NamedBytePrinter mary = new NamedBytePrinter("Mary");
NamedBytePrinter chris = new NamedBytePrinter("Chris");
frank.setPriority(Thread.MIN_PRIORITY);
mary.setPriority(Thread.NORM_PRIORITY);
chris.setPriority(Thread.MAX_PRIORITY);
frank.start();
mary.start();
chris.start();
}
}