Thread Priorities

By default, a thread inherits its priority from the program or thread that created it. It is possible to set a thread's priority using the Thread.setPriority method. A runnable thread with the highest priority is chosen first for execution. The setPriority method takes a value between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY as an argument.

For example, in RunThreads, if we were to add the following statements prior to starting the threads:

thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);

the result would be to output the thread2 stream first. The two threads would still be interleaved because the result of using the sleep method on the higher priority thread2 is
to allow execution of the lower priority thread1.

Note that the Java thread priority scheduler does not usurp any timeslicing performed on a single-processor computer system using an operating system such as Windows NT. For example, if we were to remove the sleep method (line 14) from the run method of PrintNumbersThread but set the thread priorities as described earlier, we would output
all of thread2 followed by all of thread1. On a single-processor timeslicing system, such as Windows NT, the timeslice would be large enough to output the threads in their entirety.
However, if our program were modified so that each thread output many thousands of lines, not just ten, then the timeslicing would come into play switching between threads after several thousand iterations of each thread.

No comments:

Post a Comment