Question

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.

Était-ce utile?

La 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.

Autres conseils

Program running time also accountable. You have put 6 secs to thread sleep. So Next thread will be executed. So context switching takes place.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top