首页 > 解决方案 > java变量没有volatile,线程修改cpuA中的变量切换到cpuB时一致性如何

问题描述

在一个线程中尝试此代码块

int a = 0;

a = 1; //the thread is running on cpu A

a?   //the thread is switched and running on cpu B

所以 a 可以是 0 吗?

标签: javavolatile

解决方案


不,a必须为 1,因为赋值和稍后由同一线程读取的值之间存在发生前的关系。a = 1a

如果 x 和 y 是同一线程的操作,并且 x 在程序顺序中位于 y 之前,则为 hb(x, y)。


推荐阅读