How do I set the priority of a thread?

Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases the range is less than 10). A thread gets a default priority that is the priority of the thread of execution that creates it.

But, you can also set a thread’s priority directly by calling the setPriority() method on a Thread instance. One thing to remember about thread priorities is never rely on thread priorities, because thread-scheduling priority behavior is not guaranteed.

package org.kodejava.example.lang;

public class ThreadPriority extends Thread {
    private String threadName;

    ThreadPriority(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        System.out.println("Running [" + threadName + "]");
        for (int i = 1; i <= 10; i++) {
            System.out.println("[" + threadName + "] => " + i);
            
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadPriority thread1 = new ThreadPriority("First");
        ThreadPriority thread2 = new ThreadPriority("Second");
        ThreadPriority thread3 = new ThreadPriority("Third");
        ThreadPriority thread4 = new ThreadPriority("Fourth");
        ThreadPriority thread5 = new ThreadPriority("Fifth");

        //
        // set thread1 to minimum priority = 1
        //
        thread1.setPriority(Thread.MIN_PRIORITY);

        //
        // set thread2 to priority 2
        //
        thread2.setPriority(2);

        //
        // set thread3 to normal priority = 5
        //
        thread3.setPriority(Thread.NORM_PRIORITY);

        //
        // set thread4 to priority 8
        //
        thread4.setPriority(8);

        //
        // set thread5 to maximum priority = 10
        //
        thread5.setPriority(Thread.MAX_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply