Thread Priority
Last updated
thread.setPriority(somePriorityValue);int p = thread.getPriority();public class DefaultPriorityDemo {
public static void main(String[] args) {
System.out.println("Main thread priority: " + Thread.currentThread().getPriority());
Thread t = new Thread(() -> System.out.println("New thread priority: " + Thread.currentThread().getPriority()));
t.start();
}
}Main thread priority: 5
New thread priority: 5class PriorityDemo extends Thread {
public void run() {
System.out.println("Thread Name: " + Thread.currentThread().getName() +
", Priority: " + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
PriorityDemo t1 = new PriorityDemo();
PriorityDemo t2 = new PriorityDemo();
PriorityDemo t3 = new PriorityDemo();
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.NORM_PRIORITY); // 5 (default)
t3.setPriority(Thread.MAX_PRIORITY); // 10
t1.start();
t2.start();
t3.start();
}
}Thread Name: Thread-2, Priority: 10
Thread Name: Thread-1, Priority: 5
Thread Name: Thread-0, Priority: 1for (int i = 0; i < 5; i++) {
Thread high = new Thread(() -> System.out.println("High Priority"));
Thread low = new Thread(() -> System.out.println("Low Priority"));
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
low.start();
high.start();
}High Priority
Low Priority
Low Priority
High Priority
High Priority
Low Priority
Low Priority
High Priority