小例子
public class VolatileTest {
private static volatile int INIT_VALUE = 0;
private final static 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.println("The value update to " + INIT_VALUE);
localValue = INIT_VALUE;
}
}
}, "reader").start();
// 更新线程
new Thread(()->{
int localValue = INIT_VALUE;
while (localValue < MAX_VALUE){
System.out.println("update value update to " + (++localValue));
INIT_VALUE = localValue;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "update").start();
}
}
输出结果:
若是不加volatile关键字呢?
package wangwenjun.phase2.chapter03;
import java.util.concurrent.TimeUnit;
public class VolatileTest {
private static int INIT_VALUE = 0;
private final static int MAX_VALUE = 5;
public static void main(String[] args) {
// 读线程
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
int localValue = INIT_VALUE;
while (localValue < MAX_VALUE){
if (localValue != INIT_VALUE){
System.out.println("The value update to " + INIT_VALUE);
localValue = INIT_VALUE;
}
}
}, "reader").start();
// 更新线程
new Thread(()->{
int localValue = INIT_VALUE;
while (localValue < MAX_VALUE){
System.out.println("update value update to " + (++localValue));
INIT_VALUE = localValue;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "update").start();
}
}
输出结果: