我在这里得到了一个代码,当它运行它时创建并启动一个新的线程,每秒打印一个字,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