一个 java 中 volatile 关键字的最佳演示实例,可去除/加上
INIT_VALUE
字段的volatile
修饰符,观察程序打印效果
public class VolatileTest {
private static volatile int INIT_VALUE = 0;
private static final int MAX_VALUE = 5;
public static void main(String[] args) {
new Thread(() -> {
int localValue = INIT_VALUE;
while (localValue < MAX_VALUE){
if (localValue != INIT_VALUE){
System.out.printf("the value updated to %d\n", INIT_VALUE);
localValue = INIT_VALUE;
}
}
},"READER").start();
new Thread(()->{
int localValue = INIT_VALUE;
while (INIT_VALUE < MAX_VALUE){
System.out.printf("update the value to %d\n", ++localValue);
INIT_VALUE = localValue;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"UPDATER").start();
}
}