Java Thread Priority

Thread Priority

In Java threads, you can assign priorities to threads and give execution preference to threads with higher priority.

The Thread class provides the following constants for setting priority.

    /**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

Priorities can be assigned from the lowest value 1 to the highest value 10, and the default value is 5.

When the JVM finishes executing a thread, it chooses one executable thread next and runs it. The higher the priority, the higher the probability that the thread will be executed. When priorities are the same, the thread to execute is determined by the thread scheduler’s criteria.

Example 1) Setting Thread Priority

The following example sets the priorities of two Threads to the highest and lowest values.

package com.devkuma.tutorial.thread;

public class MyThreadPriority extends Thread {

    public MyThreadPriority(String name) {
        super(name);
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(super.getName() + " thread. i=" + i);
        }
    }

    public static void main(String[] args) {
        MyThreadPriority thread1 = new MyThreadPriority("first");
        MyThreadPriority thread2 = new MyThreadPriority("second");

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

        thread1.start();
        thread2.start();
    }
}

Result:

second thread. i=0
second thread. i=1
first thread. i=0
second thread. i=2
first thread. i=1
second thread. i=3
second thread. i=4
second thread. i=5
second thread. i=6
second thread. i=7
second thread. i=8
second thread. i=9
first thread. i=2
first thread. i=3
first thread. i=4
first thread. i=5
first thread. i=6
first thread. i=7
first thread. i=8
first thread. i=9

As shown in the result, second ran more often earlier than first.