我在這裏得到了一個代碼,當它運行它時創建並啓動一個新的線程,每秒打印一個字,5秒後主方法停止線程。所以該程序將打印5個字,它確實......但不在我的家用電腦上,只在我的筆記本電腦上。在我的家用電腦上打印6次,爲什麼?Java使線程同時啓動
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;
}
}
看看那些以獲得更好的理解。 http://stackoverflow.com/questions/824110/accurate-sleep-for-java-on-windows - http://www.javatuning.com/why-is-thread-sleep-inherently-inaccurate/ – SHiRKiT 2012-01-11 19:20:04