代码如下,为什么程序不能输出end ,求指点
public class Test{
public static void main(String args[]){
R r=new R();
Thread t=new Thread(r);
t.start();
while(!r.terminate){
}
System.out.println("end");
}
}
class R implements Runnable{
public boolean terminate=false;
public void run(){
int x=0;
while(x<1000){
x++;
System.out.println(x);
}
terminate=true;
}
}
这就是线程可见性问题!子线程虽然修改了变量,但mian线程并不知道子线程修改了变量,所以一直在执行while循环,不会执行打印end的语句。
运行了,把数字从1输出到了1000,然后就是end。没有问题
把 System.out.println("end"); 放到 while 里面
你应该把terminate设置为static,不然你更改了,对象里也是不会变得
在执行run方法里你已经把全局变量重新赋值,已经为true,所以你启动线程后调用对象的变量也为true,不可能为false,所以不执行
我运行了,到1000以后就是end没问题啊?你尝试在while里加个输出看看 。
while(!r.terminate){
System.out.println(r.terminate);
}
还是有什么别的操作吗?比如多个线程同时启动,可能会造成线程不安全