如下代码一;
public class Stopdemo {
//public volatile static boolean stop = false;
public static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new StopThread());
t1.start();
TimeUnit.SECONDS.sleep(2);
stop = true;
System.out.println("赋值 stop = true");
}
static class StopThread implements Runnable{
@Override
public void run() {
int i = 0;
while(!stop) { //while(true)
i++;
}
System.out.println("运行结束: "+i);
}
}
}
运行结果为:线程不会中止推出一直循环
而若在子线程的while循环中加入System.out.println("运行中"); 则程序运行 一会后会 自动正常
Process finished with exit code 0 似乎是 赋值 stop = true 生效了导致 线程运行结束, 大神帮忙解答一下为什么 谢谢
public class Stopdemo {
//public volatile static boolean stop = false;
public static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new StopThread());
t1.start();
TimeUnit.SECONDS.sleep(2);
stop = true;
System.out.println("赋值 stop = true");
}
static class StopThread implements Runnable{
@Override
public void run() {
int i = 0;
while(!stop) { //while(true)
i++;
System.out.println("运行中");
}
System.out.println("运行结束: "+i);
}
}
}
其实这个问题就是线程安全性的可见性问题,没有加输出语句之前,线程是读不到stop 修改后的值;加了System.out.println("运行中"); 会让stop变量在while(!stop){} 这个线程中同步读到,其实这是底层深度优化后的结果 希望对你有帮助,望采纳