3

I got a code here, when it runs it creats and starts a new thread that prints a word per sec, after 5 sec the main method stops the thread. So the program will print 5 words and it does....but not on my homecomputer only on my laptop. On my home computer it prints 6 times, why?

public class Main {
  public static void main (String [] args){
    try {
      T1 t1 = new T1();
      System.out.println("Creating and staring thread 1\n");
      Thread.sleep(5000);
      t1.stopThread();
    } catch(InterruptedException ie) {}
  }
}

public class T1 extends Thread{

  private boolean alive = true;

  public T1(){
    start();
  }

  public void run(){
    while(alive){
      try {
        System.out.println("Tråd T1: Tråd 1");
        Thread.sleep(1000);
      } catch(InterruptedException ie) {}
    }
  }
  public void stopThread(){
    alive = false;
  }
}
unholysampler
  • 17,141
  • 7
  • 47
  • 64
199user911
  • 405
  • 2
  • 6
  • 10

2 Answers2

9

Both results are correct. Sleep times are approximate.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • 2
    Take a look at those to get a better understand. http://stackoverflow.com/questions/824110/accurate-sleep-for-java-on-windows - http://www.javatuning.com/why-is-thread-sleep-inherently-inaccurate/ – SHiRKiT Jan 11 '12 at 19:20
8

You are lucky that your program stops printing at all. You have a program that has undefined behavior and it could run forever on some machines. You must make alive volatile, otherwise there is no guarantee that your secondary thread will ever see the change made to alive in the main thread.

Look at the end of the Java language specification chapter on memory; they basically give your example as something that must not be done.

That being said, you might still get 6 printed lines instead of 5 from the inaccuracy of Thread.sleep.

toto2
  • 5,306
  • 21
  • 24