Atom类源码分析

本文探讨了Java并发编程中volatile关键字的局限性,通过一个示例说明其无法确保变量的原子性。接着,作者深入分析了AtomInteger类的源码,特别是其volatile变量value,解释了为何AtomInteger能保证原子性,为读者揭示了Java并发编程中的原子操作原理。
摘要由CSDN通过智能技术生成

今天再看《Java并发编程实践》的时候提到了这样一句话:volatile关键字只能保证变量的可见性,无法保证变量的原子性。

当时没懂,搜了几个事例分析了一下,顺便也分析一下可以保证原子性的atom类的源码(这里以AtomInteger为例)


先看一下volatile无法保证原子性的事例:

class IntegerTestThread implements Runnable{

	public void run() {
		int x = 0;
		while(x<1000){
			atom.ai.addAndGet(1);
			atom.integer++;
			atom.i++;
			x++;
			
		}
		atom.endThread.addAndGet(1);
	}
	
}

public class atom {
	
	public static AtomicInteger ai = new AtomicInteger();
	
	public static volatile Integer integer = new Integer(0);
	
	public static volatile int i = 0;
	
	public static AtomicInteger endThread = new AtomicInteger();
	
	public static void main(String[] args) throws InterruptedException {
		new atom().testAtom();
	}
	
	public void testAtom() throws InterruptedException{
		for(int i=0;i<100;i++){
			new Thread
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值