What is Thread Scheduling in Java?

Tech Insights

Execution of multiple threads/tasks on a single processor is called Thread Scheduling.
Scheduling can mainly be of two types.

1) Preemptive scheduling
2) Time-sliced scheduling

In Preemptive scheduling, the thread with the highest priority runs first. it keeps running until it reaches wait or dead stage or a higher priority thread comes.
In Time-sliced scheduling, the thread executes for a predefined slice of time.

The JVM basically uses Preemptive scheduling. All Java threads have a priority and the thread with he highest priority is scheduled to run by the JVM.

The Thread class contains three integer priority constants
1. MIN_PRIORITY [1]
2. NORM_PRIORITY [5]
3. MAX_PRIORITY [10]

The default thread priority is NORM_PRIORITY. To get and set a thread’s priority we have getPriority() and setPriority() respectively.

BUT WE CANNOT rely on thread priority as a guarantee that the highest priority thread will always be running; the operating system has the final say as actual Scheduling depends on the OS which can be Preemptive or Time-sliced.

In case two threads have the same priority,
– a FIFO ordering is followed if the Operating System (OS) uses Preemptive.
– Java quickly switches between them in round-robin fashion if the OS uses Time-slicing.