Java Thread Scheduling
Consider the simple computer game -
The person is moving from left to right. At the same time diamond shapes are blinking at the bottom.
What is use of Thread in above example :
- In the single processor environment, Single thread will run at a time. Time between the execution of two threads is very small
- As time between execution of two threads is very small we get an illusion of the concurrency
- Executing the multiple threads on single CPU based on some priority order is called as scheduling.
- JRE supports simple algorithm called fixed-priority scheduling which schedules threads on the basis of their priority relative to other Runnable threads.
Thread Scheduler :
- Thread Scheduler is part of JVM.
- Thread Scheduler decides which thread should run and which thread should stop running.
- Thread Scheduler selects only one thread at a time for single processor.
- We cannot predict which thread Thread Scheduler will select.
Consider the following diagram -
In the above method of scheduling the multiple threads shares the single CPU by sharing the time.
Thread Scheduling Summary :
- In single processor environment, threads shares CPU with other threads.
- The execution of multiple threads on a single CPU based on some order is called scheduling.
- The JDK provides scheduling algorithm called fixed-priority scheduling.
- Each thread has a numeric priority between MIN_PRIORITY and MAX_PRIORITY
- When multiple threads are ready for execution then the thread having highest priority will be selected.
- When multiple threads having the same priority then any random thread will be selected.
- When thread stops execution then lower-priority thread starts their execution.
- yield() Method : Thread pauses execution of current thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute.