Thread Scheduler Java

Thread Scheduler Java

Observe the outputs in the screenshot (order of execution) when the following program is run number of times.

public class Demo extends Thread
{
  public void run() 
  {
    int k = 0;
    for (int i = 0; i < 3; i++)
    {
      k++; 
      k--;   
   }
   System.out.println(k);
  }
  public static void main(String[] args) 
  {
    Demo d1 = new Demo();
    Demo d2 = new Demo();
    d1.start();
    d2.start();
    System.out.println("Over");
  }
}

Thread Scheduler Java

Two anonymous objects of Demo thread are created and started. Both calls the same run() method and increment and decrement the k variable. In the program, there are three threads – two of you and one predefined main thread. Observe their output of execution, it is not consistent. Why? The scheduler is a very complex algorithm and executes different ways (sometimes, unpredicted) when called at different times. Thread scheduler operates not only our program threads but JVM and operating system own threads and also any processes started on the system which amount to thousands of threads. Of these threads, some may be in born state, some may be in blocked state and some in runnable state. When ever a running thread is blocked, imbalance in the priority order occurs and scheduler comes into action and recalculates. Same process occurs when a thread joins the pool of threads. In this calculating and recalculating, the alogirithm may not work properly as algorithm should take the properties of the threads.

3 thoughts on “Thread Scheduler Java”

  1. Bhavani Prasad Rao Ejanthkar

    Hi Sir,
    First of all, I would like to thank you for sharing the java resources for learners. Can you please give me some real-time applications that uses the thread scheduling mechanism of various domains like Banking or other applications ? I would be more than happy to hear more examples from you.

    Thank you,
    Regards,
    Bhavani Prasad.

Leave a Comment

Your email address will not be published.