Search code examples
javamultithreadingsleeprunnable

Running time calculation in multi threading


In my code:

public class thread1 implements Runnable {

public static void main(String[] args) {
    thread1 d = new thread1();
    new Thread(d).start();
    Thread t1 = new Thread(d);
    t1.start();
}

@Override
public void run() {
    for (int i = 0; i < 3; i++) {
        sleep1();
        sleep2();
    }
}

void sleep1() {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

synchronized void sleep2() {
    try {
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

I ran my code and calculate its running time to finished.

The minimum time to finished was 7 seconds.

Why?

It should be 6 seconds, Because 3loops * 2seconds = 6seconds.


Solution

  • Because of context switching. sleep() is not a guaranteed amount of time, but is subject to other things going on in the system. It will try to come back, but may not succeed. Also, probably rounding in your IDE.