Setting thread priorities

Setting a threads priority can be very useful if one thread has more critical tasks to perform than another.
The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has.
The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set, a Thread instance has the priority level of 5.
In the first example below no priorites are set, so both threads have the priority level 5. The TestThread class implements the Runnable interface and in its
run() method loops from 1 to 10 and output the number along with its Thread id, which is passed to the constructor.

Since both threads have the same priority, the output will be a mix between them and could look like this:

The output could look different from on execution to another since we have no control of how the CPU will prioritize them.

If we set the priority on the threads we still haven’t got exact control of the execution, but at least we can tell the CPU which one we think is
most important. The next example is identical to the one above except for the lines where the priority of the threads are set:

The output from the code looked like this when executed:

It is however not certain that the first thread will be prioritized to finish before the second thread starts every time.
It is, as mentioned earlier, up to the CPU to decide.

Search for more Java info on this site here:
Custom Search

Please type any questions here.