![]() |
VOOZH | about |
Java supports multithreading, where multiple threads run concurrently and the Thread Scheduler decides their execution order. Each thread is assigned a priority (1–10) that influences scheduling but does not guarantee execution order.
LowPriorityThread is running with priority 1 HighPriorityThread is running with priority 10
Explanation:
Java provides three constant values in the Thread class:
We can use the following methods of the Thread class to manage thread priority:
Thread-2 with priority 5 Thread-1 with priority 1 Thread-3 with priority 10
Explanation: The program creates three threads, assigns them different priorities (1, 5, and 10), and starts them using start(). Each thread runs concurrently and prints its name and priority, but the execution order is not fixed and depends on the scheduler.
Note: The output order may vary because thread scheduling depends on the JVM and the underlying operating system.
If multiple threads have the same priority, their execution order is decided by the thread scheduler. The example below demonstrates this, followed by an explanation of the output for better conceptual and practical understanding.
t1 priority: 5 t2 priority: 5 Thread-1 is running with priority 5 Thread-0 is running with priority 5
Explanation: The main thread sets its priority to 5, and both t1 and t2 inherit this priority when created. When start() is called, both threads run concurrently and print their details, and since they have the same priority, their execution order depends on the OS scheduler.