In this lesson, you will learn.
In theory, threads of equal priority should get equal access to the CPU.
Although thread priority does not guarantee a specific order, higher-priority threads generally get a preference for execution over lower-priority ones.
Java thread priorities range from 1 to 10.
The constants Thread.MIN_PRIORITY, Thread.NORM_PRIORITY, and Thread.MAX_PRIORITY represent values 1, 5, and 10, respectively.
Default Priority: All threads have a default priority of Thread.NORM_PRIORITY (5).
package threadpriority;
public class ThreadPriorityExample extends Thread {
public ThreadPriorityExample(String name) {
super(name); // Set the name of the thread
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(this.getName() + " with priority "
+ this.getPriority() + " Loop " + i);
try {
Thread.sleep(500); // Sleep for a half second
} catch (InterruptedException e) {
System.err.println(this.getName() + " interrupted.");
}
}
System.out.println(this.getName() + " finished.");
}
public static void main(String[] args) {
ThreadPriorityExample t1 = new ThreadPriorityExample("Low Priority Thread");
ThreadPriorityExample t2 = new ThreadPriorityExample("Normal Priority Thread");
ThreadPriorityExample t3 = new ThreadPriorityExample("High Priority Thread");
// Set priorities for all threads
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
// Start threads
t1.start();
t2.start();
t3.start();
}
}
Low Priority Thread with priority 1 Loop 0
Normal Priority Thread with priority 5 Loop 0
High Priority Thread with priority 10 Loop 0
Low Priority Thread with priority 1 Loop 1
Normal Priority Thread with priority 5 Loop 1
High Priority Thread with priority 10 Loop 1
Normal Priority Thread with priority 5 Loop 2
Low Priority Thread with priority 1 Loop 2
High Priority Thread with priority 10 Loop 2
High Priority Thread with priority 10 Loop 3
Normal Priority Thread with priority 5 Loop 3
Low Priority Thread with priority 1 Loop 3
Normal Priority Thread with priority 5 Loop 4
Low Priority Thread with priority 1 Loop 4
High Priority Thread with priority 10 Loop 4
High Priority Thread finished.
Normal Priority Thread finished.
Low Priority Thread finished.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.