🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Thread Priority in Java  


Introduction
  • Thread Priority in Java defines the importance level of a thread, which helps the thread scheduler decide the order in which threads should be executed.
  • In Java, there are 3 pre-defined priorities for every thread:
    • public static int MIN_PRIORITY = 1 → Lowest priority
    • public static int NORM_PRIORITY = 5 → Default priority
    • public static int MAX_PRIORITY = 10 → Highest priority
  • These three are the pre-defined priorities, but in Java a thread’s priority can be assigned any value from 1 to 10. But it cannot be less than 1 and cannot be greater than 10.
  • Real-World Examples where Thread Priority is used:
    • Online Shopping Application: Payment processing thread can have higher priority than product recommendation threads.
    • Chat Application: Message sending/receiving threads get higher priority, while background emoji loading runs with lower priority.
    • Banking System: Fund transfer threads have higher priority compared to notification or report generation threads.
  • For Thread Priority, Java has provided two important methods:
    • public final void setPriority(int newPriority)
      • Used to set the priority of a thread.
      • Value must be between 1 (MIN_PRIORITY) and 10 (MAX_PRIORITY).
      • Must be called before or after start(), but should be set before the thread starts running.
    • public final int getPriority()
      • Returns the current priority value of the thread.
  • Program:
    class MyThread extends Thread
    {
        @Override
        public void run()
        {
            System.out.println(getName() + " is running with priority: " + getPriority());
        }
    }
    
    public class ThreadPriorityDemo
    {
        public static void main(String[] args)
        {
            MyThread low = new MyThread();
            MyThread high = new MyThread();
    
            low.setName("Low-Priority-Thread");
            high.setName("High-Priority-Thread");
    
            // Set priorities
            low.setPriority(Thread.MIN_PRIORITY);   // 1
            high.setPriority(Thread.MAX_PRIORITY);  // 10
    
            // Start low first, then high
            low.start();
            high.start();
        }
    }
  • Key Points about Thread Priority:
    • Each thread in Java has a priority represented by an integer value between 1 (lowest) and 10 (highest).
    • By default, every thread is assigned a priority of 5 (normal priority).
    • Thread priorities are hints to the thread scheduler about the relative importance of threads.
    • Higher priority threads are more likely to be executed before lower priority threads, but this behavior is not guaranteed.