Java并发之AtomicLong类

简介:java.util.concurrent(JUC)有个atomic小型工具包,支持单个变量上的无锁线程安全编程。
在这里插入图片描述
以上是这个包下的所有相关类,java.util.concurrent.atomic.AtomicLong类只是其中的一种,提供了可以被原子地读取和写入的底层long值的操作,并且还包含高级原子操作。下面我们一来学习这个类的方法及用途。
方法:
在这里插入图片描述
示例:
以下AtomicLongTest程序显示了在基于线程的环境中使用AtomicLong的计数器的安全实现,帮助我们更好的理解为什么使用。

import java.util.concurrent.atomic.AtomicLong;

public class AtomicLongTest {
	
	static class Counter{
		//AtomicLong
		private AtomicLong a = new AtomicLong(0);
		//long
		private long num=0;
		public void increment(){
			a.getAndIncrement();
		}
		
		public long value(){
			return a.get();
		}

		
		
	}
	
	public static void main(String[] args) throws InterruptedException {
		final Counter counter = new Counter();
		
		//1000 threads
		for (int i = 0; i < 1000; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					counter.increment();
					counter.num++;
				}
			}).start();
		}
		Thread.sleep(6000);
		System.out.println("Final number (should be 1000): " + counter.value());
		
		
		System.out.println("Final long (not 1000): " + counter.num);
	}

}

结果
在这里插入图片描述
多次运行,我们会发现AtomicLong值始终是100,long值却不一定,由此可见AtomicLong类保证了并发下数值的一致性。为什么AtomicLong可以呢,看下他的源码实现
在这里插入图片描述
在这里插入图片描述
由此可见,AtomicInteger.getAndIncrement()的实现用了乐观锁技术,调用了类sun.misc.Unsafe库里面的 CAS算法,用CPU指令来实现无锁自增。synchronized关键字的独占锁相比,效率会高很多。看到这里引出了一个很核心的东西- CAS算法。
附上文章链接-什么是CAS算法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值