Java — Thread Priorities | Code Factory
2 min readMay 28, 2020
Index Page : Link
Donate : Link
WordPress Blog : Link
- Every Thread in Java has some priority. It may be default priority generated by JVM or customized priority provided by programmer.
- The valid range of thread priorities is 1 to 10. Where 1 is minimum priority and 10 is more priority.
- Thread class defines the following constant to represent some standard priorities.
Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
Thread.MAX_PRIORITY
- Thread schedular will use priorities while allocating processor. The thread which is having highest priority will get chance first.
- If 2 threads have same priority then we can’t expect exact execution order, It depends on Thread Schedular.
- Thread class defines the following methods to get and set priority of a thread
/* Returns this thread's priority. */
public final int getPriority()/* Changes the priority of this thread. */
public final void setPriority(int newPriority)
- In setPriority method allowed values range 1 to 10 otherwise RE :
IllegalArgumentException
t.setPriority(7); // ✓
t.setPriority(17); // X
- The default priority only for the main thread is 5. But for all remaining threads default priority will be ingerited from parent to child. That is whatever priority thread has the same priority be there for the child thread.
package com.example.thread;public class ThreadTest {
public static void main(String... args) {
System.out.println(Thread.currentThread().getPriority());
//Thread.currentThread().setPriority(15); // RE : IllegalArgumentException
Thread.currentThread().setPriority(7);
MyThread t = new MyThread();
System.out.println(t.getPriority());
}
}class MyThread extends Thread {
}
Output :
5
7