class StopTester implements Runnable {
//private volatile boolean stop = false;
private boolean stop = false;
public void stopMe() {
stop = true;
}
@Override
public void run() {
while(!stop) {}
System.out.println("Thread stopped.");
}
}
public class TestVolatile {
public static void main(String[] args) throws Exception {
StopTester tester = new StopTester();
Thread thread = new Thread(tester);
thread.start();
Thread.sleep(1000);
System.out.println("Try stop...");
tester.stopMe();
Thread.sleep(1000);
}
}
如果用了volatile
,Thread stopped.
就可以顺利输出,如果不用就无法输出,何解?tester.stopMe()
这行代码是运行在主线程还是运行在thread
线程呢?
如果不用valatile 第一次访问stop的时候通过this引用把值读到栈上 之后每次就直接从栈上读值了 你改了stop他还是这样读 所以循环卡在那里不会往下走
很明显在主线程