public class VolatileVisualTest {
// volatile 无法保证原子性
public static final int clientTotal = 1000;
public static final int threadTotal = 200;
private static int i = 0;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (i == 0) {
}
System.out.println("t1 : " + i);
});
Thread t2 = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
});
t1.start();
t2.start();
}
private static void update() throws Exception {
i++;
}
}
thread1 一开始从主存里面读取到i的值时0,然后放入到该线程的工作内存之中,thread2 也从主存中读取i的值时0,然后执行i++,将1写入到线程2的工作内存中并刷写到主存,但是因为变量没有volatile修饰,只是个普通变量,thread1没法感知到thread2对i的修改,就只能还是一开始读取的i=0的值,导致循环退不出去。
此时无法thread1 无法退出循环,就是因为该变量没有被volatile修复,导致thread 2更新的i的最新值无法被thread1 看到,所有循环退不出去。所以如果需要改变该问题,就应该使用volatile修饰i变量.
private volatile static int i = 0;