Unit 4 Thread Priority
Unit 4 Thread Priority
THREAD PRIORITY
4. THREAD PRIORITY:
• In Java, each thread has a priority, which helps the system decide the order in which threads run. The
priority is a number from 1 (lowest) to 10 (highest), with the default being 5. You can set a thread's
priority using setPriority() and get it using getPriority(). A thread with a higher priority gets more CPU
time than a lower-priority one, but it’s not guaranteed — it depends on the system's thread scheduler.
• In Java, multithreading allows a program to run multiple threads at the same time. When many threads
are running together, the system needs to decide which thread to run first. This is where Thread
Priority comes in.
• Each thread in Java has a priority, which is a number between 1 and 10. A thread with a higher
priority is considered more important and may be executed before lower-priority threads.
However, it is not guaranteed because the final decision is made by the Thread Scheduler, which
is dependent on the operating system (Windows, Linux, etc.).
• The default priority of any thread is 5, which is called NORM_PRIORITY. You can change the
priority using the setPriority(int) method and check it using getPriority().
• Types of Thread Priority
• Java provides three predefined constants for thread priorities:
• Java provides three predefined constants for thread priorities:
Example:
}
public class TestPriority {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("LowPriorityThread");
t2.setName("HighPriorityThread");
t1.start();
t2.start();
}
}
Thank You