不一定。
如下测试代码:
int a = 0;
volatile int b = 0;
@Test
public void testVolatile() throws InterruptedException {
Thread thread1 = new Thread(() -> sleepAndCount());
Thread thread2 = new Thread(() -> sleepAndRead());
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
private void sleepAndCount() {
System.out.println("++a:"+ ++a);
System.out.println("++b:"+ ++b);
}
private void sleepAndRead() {
System.out.println("b:"+b);
System.out.println("a:"+a);
}
输出结果: