线程可见性

可以看到程序变量running没volatile是死循环

加了volatile成功输出

线程可见性和关键字volatile_死循环

 

线程可见性和关键字volatile_i++_02

public class VolitaleTest {
private static volatile boolean running = true;
public static void main(String[] args) {

Thread thread = new Thread(() ->{
long i =0L;
while (running){
i++;
}
System.out.println("end and i = " + i);
});
thread.start();
try {
//暂停1秒
Thread.sleep(1000);
running = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}