我这里有一段代码,当它运行时,它会创建并启动一个每秒打印一个单词的新线程,5 秒后 main 方法会停止该线程。所以该程序将打印 5 个单词,它确实......但不是在我的家用电脑上,只在我的笔记本电脑上。在我家的电脑上它打印了 6 次,为什么?
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;
}
}
最佳答案
两个结果都是正确的。 sleep 时间是近似值。
关于Java使线程同时启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8825247/