In Java, every thread has a priority that helps the operating system determine the order in which threads are scheduled for execution. The default priority of a thread in Java is determined by the priority of the thread that creates it. Specifically, a new thread inherits the priority of the thread from which it was created.
The default priority for the main thread, and hence for any threads created directly from it if not explicitly set, is Thread.NORM_PRIORITY
. The value of Thread.NORM_PRIORITY
is 5.
Java provides a range of thread priorities from 1 to 10, where:
Thread.MIN_PRIORITY
is 1,Thread.NORM_PRIORITY
is 5,Thread.MAX_PRIORITY
is 10.
Here is a simple example to demonstrate this:
public class ThreadPriorityExample {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("Running thread name: " + Thread.currentThread().getName());
System.out.println("Running thread priority: " + Thread.currentThread().getPriority());
});
System.out.println("Main thread priority: " + Thread.currentThread().getPriority());
t.start();
}
}
In this example:
- The main thread's priority is printed, which would typically be 5 (
Thread.NORM_PRIORITY
). - A new thread
t
is created and started without setting its priority, so it inherits the priority of the main thread, which is also printed and will show as 5.
You can change the priority of a thread using the setPriority(int priority)
method on a Thread
object, where priority
is an integer value between Thread.MIN_PRIORITY
and Thread.MAX_PRIORITY
. Here's how you might set a different priority:
Thread t = new Thread(() -> {
System.out.println("Running thread name: " + Thread.currentThread().getName());
System.out.println("Running thread priority: " + Thread.currentThread().getPriority());
});
t.setPriority(Thread.MAX_PRIORITY); // Setting the thread priority to 10
t.start();
Remember, thread priorities are hints to the thread scheduler and do not guarantee the order of thread execution, which is highly dependent on the thread scheduler implementation of the operating system. In some cases, thread priorities may have little or no effect on the order in which threads are executed.
Post a Comment