03 volatile
public class T {
// 不加 volatile,程序永远不会停下
/* volatile */ boolean running = true;
public void m() {
System.out.println("m start");
while (running) {
System.out.println("running");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("m end");
}
public static void main(String[] args) {
T t = new T();
/*
需要注意,如果直接执行 t.m() 而不是另起线程,那么无论是否加 volatile,程序都不会停下,循环判断中的 running 一直为 true
*/
new Thread(t::m).start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.running = false;
System.out.println(t.running);
}
}最后更新于