199*_*911 3 java multithreading
我在这里得到一个代码,当它运行时创建并启动一个新的线程,每秒打印一个单词,5秒后主方法停止线程.所以该程序将打印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;
}
}
Run Code Online (Sandbox Code Playgroud)
两个结果都是正确的.睡眠时间是近似值.