volatile无法保证原子性
/**无法保证原子性
* @author 雪辞
*
*/
public class TestAtomicity {
private volatile static int count=0;
public static void main(String[] args) {
//启动十个线程
for (int i = 0; i <10; i++) {
Thread thread=new Thread(()->{
//每个线程执行1000次自增
for (int j = 0; j < 1000; j++) {
count++;
}
});
thread.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(count);
}
}
结果:

本应该是10000,但是总<=10000,不满足原子性,原因稍微提一下是主内存被更改,工作内存值失效,但是自增的次数已经使用而值没有被自增完赋值给主内存。
想要深入了解待之后更新!
学习不是一蹴而就,而是日复一日

浙公网安备 33010602011771号