Thread Scheduler in Java: Managing Thread Execution and Priority
Understand the role of the thread scheduler in Java, a critical component responsible for selecting and managing threads for execution based on criteria like thread priority and time of arrival. Learn how the scheduler handles threads in the runnable state to optimize multitasking.
Thread Scheduler in Java
- A component of Java that decides which thread to run or execute and which thread to wait is called a thread scheduler in Java.
- A thread is chosen by a thread scheduler only if it is in the runnable state.
- If there is more than one thread in the runnable state, the thread scheduler picks one of the threads based on specific criteria: Priority and Time of Arrival.
Factors for Scheduling a Thread
PriorityPriority of each thread lies between 1 to 10. If a thread has a higher priority, it means that thread has a better chance of getting picked up by the thread scheduler.
Time of ArrivalIf two threads of the same priority enter the runnable state, the arrival time of the thread is considered. The thread that arrived first gets the preference.
Thread Scheduler Algorithms
First Come First Serve Scheduling
In this algorithm, the scheduler picks the threads that arrive first in the runnable queue.
Threads | Time of Arrival |
---|---|
t1 | 0 |
t2 | 1 |
t3 | 2 |
t4 | 3 |
In the above table, Thread t1 will be processed first, and Thread t4 will be processed last.
Time-Slicing Scheduling
This algorithm provides time slices to the threads to avoid infinite blocking (starvation). After a specified time, the running thread has to give up the CPU, allowing other threads to execute.
In the diagram below, each thread is given a time slice of 2 seconds. After 2 seconds, the first thread leaves the CPU, and the CPU is then captured by the next thread.
Preemptive-Priority Scheduling
This algorithm is related to the priority of the threads. The scheduler picks the thread with the highest priority. Since it is also preemptive, time slices are provided to avoid starvation.
Working of the Java Thread Scheduler
Let's understand the working of the Java thread scheduler with an example. Suppose there are five threads with different arrival times and priorities. The thread scheduler decides which thread will get the CPU first based on these criteria.
The scheduler selects the thread with the highest priority. If a higher priority thread arrives while another thread is running, the current thread is preempted, and the higher priority thread gets the CPU time.
If two threads have the same priority and arrival time, the FCFS algorithm is used, giving preference to the thread that arrived first.