0% completed
Thread priority in Java is a hint to the thread scheduler about the relative importance of a thread compared to others. Each thread has an integer priority that helps determine the order in which threads are scheduled for execution. Although the scheduler behavior is platform-dependent and not guaranteed, thread priority can influence which thread is more likely to be executed sooner when multiple threads are waiting for CPU time.
Priority Range: Java thread priorities range from 1 (lowest) to 10 (highest).
Default Priority: Threads by default have a priority of 5, represented by Thread.NORM_PRIORITY
.
Minimum and Maximum Priorities:
Thread.MIN_PRIORITY
is 1.Thread.MAX_PRIORITY
is 10.Setting and Getting Priority:
setPriority(int newPriority)
to set a thread's priority.getPriority()
to retrieve a thread's current priority.Below is a summary table of thread priorities:
Priority Level | Constant | Value |
---|---|---|
Minimum Priority | Thread.MIN_PRIORITY | 1 |
Normal Priority | Thread.NORM_PRIORITY | 5 |
Maximum Priority | Thread.MAX_PRIORITY | 10 |
This example creates two threads with different priorities. One thread is given the maximum priority, and the other the minimum. The code prints each thread's name, priority, and a counter to illustrate how priorities are set.
Example Explanation:
Thread-1
and Thread-2
) are created.Thread-1
is assigned the maximum priority (10) using setPriority(Thread.MAX_PRIORITY)
.Thread-2
is assigned the minimum priority (1) using setPriority(Thread.MIN_PRIORITY)
.start()
.Thread.sleep(500)
call pauses each thread for 0.5 seconds between counts, allowing for observable interleaving.Thread-1
may run more frequently, exact scheduling is managed by the JVM and may vary by system.Thread priority in Java provides a mechanism to hint the scheduler about the relative importance of threads. With priorities ranging from 1 (minimum) to 10 (maximum), you can influence which threads are more likely to be executed sooner. Although thread priority is not a guarantee and is platform-dependent, it is a useful tool for managing thread execution in concurrent applications.
.....
.....
.....