我在这里得到一个代码,当它运行时创建并启动一个新的线程,每秒打印一个单词,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;
}
}
解决方法:
你很幸运,你的程序完全停止打印.你有一个程序具有未定义的行为,它可以在某些机器上永远运行.你必须使volatile变为活动,否则无法保证你的辅助线程会在主线程中看到对alive的更改.
看一下Java语言规范chapter on memory的结尾;他们基本上把你的榜样作为一些不能做的事情.
话虽这么说,你可能仍然会得到6条打印线,而不是Thread.sleep的不准确性.
标签:java,multithreading
来源: https://codeday.me/bug/20190712/1442348.html