-
Notifications
You must be signed in to change notification settings - Fork 14
Java Thread Priority Example
Ramesh Fadatare edited this page Aug 29, 2018
·
3 revisions
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. 3 constants defined in Thread class:
- public static int MIN_PRIORITY
- public static int NORM_PRIORITY
- public static int MAX_PRIORITY Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
public class ThreadPriorityExample {
public static void main(final String[] args) {
final Runnable runnable = () -> {
System.out.println("Running thread name : " + Thread.currentThread().getName() +
" and it's priority : " + Thread.currentThread().getPriority());
};
final Thread thread1 = new Thread(runnable);
final Thread thread2 = new Thread(runnable);
final Thread thread3 = new Thread(runnable);
final Thread thread4 = new Thread(runnable);
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.NORM_PRIORITY);
thread3.setPriority(Thread.MAX_PRIORITY);
thread4.setPriority(2);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
Output:
Running thread name : Thread-0 and it's priority : 1
Running thread name : Thread-1 and it's priority : 5
Running thread name : Thread-2 and it's priority : 10
Running thread name : Thread-3 and it's priority : 2