The following article demonstrates How to Use Thread Priorities in Java.

Problem Statement

Demonstrate through a program that high-priority thread gets more CPU attention than a low-priority thread.

Solution

In Java, you can demonstrate that a high-priority thread gets more CPU attention than a low-priority thread by creating two threads, one with high priority and one with low priority, and observing how they are scheduled by the operating system. Threads with higher priority are supposed to get more CPU time compared to lower-priority threads.

The following Java program that demonstrates this concept.

public class PriorityDemo {
    public static void main(String[] args) {
        // Create a high-priority thread
        Thread highPriorityThread = new Thread(new MyRunnable(), "HighPriorityThread");
        highPriorityThread.setPriority(Thread.MAX_PRIORITY);

        // Create a low-priority thread
        Thread lowPriorityThread = new Thread(new MyRunnable(), "LowPriorityThread");
        lowPriorityThread.setPriority(Thread.MIN_PRIORITY);

        // Start both threads
        highPriorityThread.start();
        lowPriorityThread.start();
    }

    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + " - Count: " + i);
                try {
                    Thread.sleep(100); // Sleep for 100 milliseconds
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In this program:

  1. We create two threads, highPriorityThread and lowPriorityThread, with different priorities.
    • highPriorityThread is set to have the maximum priority using Thread.MAX_PRIORITY.
    • lowPriorityThread is set to have the minimum priority using Thread.MIN_PRIORITY.
  2. Both threads run the same MyRunnable task, which simply counts from 1 to 5 with a small delay between each count.
  3. We start both threads, allowing them to run concurrently.

Since highPriorityThread has higher priority than lowPriorityThread, you should observe that highPriorityThread is more likely to run before lowPriorityThread and may complete its tasks faster. However, the exact behavior may vary depending on your system’s thread scheduling and CPU availability.


Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites