Java — Thread Priorities | Code Factory

  • 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)
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 {

}
5
7

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Change the Color of a Single Navigation Link in Squarespace

Creating a DevOps toolbox for Gitlab-CI

The Liberators News — Dec 2019

Lore: where your drive is connected

hello world

Why learn JavaScript?

Hacker Type — nail your Xcode demo with auto code completion

My DSAID Internship Experience

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Unit Testing Apache Camel

From JAVA 9 to JAVA 15: Evolutions and new features — Part 1

Concurrency in Java: Executor Service (Part 1)

Comparison of Java 8 vs Java 17, Should You Upgrade?