Search code examples
javamultithreadingthread-sleep

Time schedular in java with Thread.sleep


  import java.util.Date;

  import javax.xml.crypto.Data;

  public class Task1 {
    public static void main(String[] args) {
      // run in a second
      final long timeInterval = 4000;
      Data now = null;
      Runnable runnable = new Runnable() {
        public void run() {
          while (true) {
            // ------- code for task to run
            System.out.println("Hello !!"+new Date());
            for(int i=0;i<10000;i++){
              System.out.println("Hello !!");
            }

            // ------- ends here
            try {
              Thread.sleep(timeInterval);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
       }

      };

      Thread thread = new Thread(runnable);
      thread.start();
    }
  }

I read a tutorial regarding the scheduling of threads.I want to understand that the code runs fine and executes thread after 4 seconds but if the time taken by for loop suppose comes out to be 1 second then total time will be 1+4 5 seconds. I do not want to executor service .Just normal Thread class.Can anyone explain how this program is working.


Solution

  • You are right that sleep is in addition to the time taken in the loop already.

    Even if you calculated the sleep time remaining, it still could take longer as there is no guarantee as to how quickly sleep will wake up. It can be tens of milli-seconds later sometimes.

    What ExecutorService does is calculate when it should wake from the first run and ensure any delays don't accumulate. It uses System.nanoTime() so corrections in the wall clock don't impact the period.