群友发了一段代码,说变量没有加volatile,但是依旧可见,代码大致如下:
public class StopThreadTest implements Runnable {
private boolean flag = true;
public static void main(String[] args) throws InterruptedException {
StopThreadTest stopThreadTest = new StopThreadTest();
Thread thread = new Thread(stopThreadTest);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopThreadTest.flag = false;
}
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println(i);
}
System.out.println("计数器已经停止");
}
}
这段代码甚至差点让我改变三观。。。
经过若干测试后,发现问题出在System.out.println(i); 这个方法包含一个加锁的动作,如下:
image.png
网友评论