Skip to main content

Practical-38

Write a java program which shows the Priority in Threads.


Introdution

In Java, threads can be assigned priorities from 1 to 10 where 1 is the minimum priority and 10 is the maximum priority. Threads with higher priority take precedence over threads with lower priority when the two are competing for the same processing resource. At the same time, multiple threads with the same priority can be scheduled by the JVM simultaneously by using either a round robin or a random approach.

Code

public class ThreadPriorityDemo {
public static void main(String[] args) {
// creating two threads
Thread t1 = new Thread(() -> {
System.out.println("Thread 1 is running");
});
Thread t2 = new Thread(() -> {
System.out.println("Thread 2 is running");
});

// setting priorities of threads
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);

// starting threads
t1.start();
t2.start();
}
}

Output

Thread 1 is running
Thread 2 is running
Explanation

The code creates two threads, with one thread set to maximum priority and the other set to minimum priority. When we run the program, the thread with maximum priority always takes precedence over the other thread and is executed first.