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.

Java Threading Example

What is use of Thread in above example :

  1. In the single processor environment, Single thread will run at a time. Time between the execution of two threads is very small
  2. As time between execution of two threads is very small we get an illusion of the concurrency
  3. Executing the multiple threads on single CPU based on some priority order is called as scheduling.
  4. JRE supports simple algorithm called fixed-priority scheduling which schedules threads on the basis of their priority relative to other Runnable threads.

Thread Scheduler :

  1. Thread Scheduler is part of JVM.
  2. Thread Scheduler decides which thread should run and which thread should stop running.
  3. Thread Scheduler selects only one thread at a time for single processor.
  4. We cannot predict which thread Thread Scheduler will select.

Consider the following diagram -
Thread Scheduling
In the above method of scheduling the multiple threads shares the single CPU by sharing the time.

Thread Scheduling Summary :

  1. In single processor environment, threads shares CPU with other threads.
  2. The execution of multiple threads on a single CPU based on some order is called scheduling.
  3. The JDK provides scheduling algorithm called fixed-priority scheduling.
  4. Each thread has a numeric priority between MIN_PRIORITY and MAX_PRIORITY
  5. When multiple threads are ready for execution then the thread having highest priority will be selected.
  6. When multiple threads having the same priority then any random thread will be selected.
  7. When thread stops execution then lower-priority thread starts their execution.
  8. yield() Method : Thread pauses execution of current thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute.