JUC源码解析(一)AtomicInteger

来说一个最基本的吧,AtomicInteger
废话不多说,上代码吧

  1. // setup to use Unsafe.compareAndSwapInt for updates
  2. //底层指令的实例引用
  3. private static final Unsafe unsafe = Unsafe.getUnsafe();
  4. //内存首地址的偏移量
  5. private static final long valueOffset;
  6. //静态方法
  7. static {
  8. try {
  9. valueOffset = unsafe.objectFieldOffset
  10. (AtomicInteger.class.getDeclaredField("value"));
  11. } catch (Exception ex) { throw new Error(ex); }
  12. }
  13. //存放int值,线程可见
  14. private volatile int value;

以上就是AtomicInteger重要的成员变量以及静态方法
1.unsafe 其实就是负责与CAS相关的操作实现,由sun.mic包提供
2.valueOffset的值是变量value的内存首地址的偏移量。,它在AtomicInteger被加载时就被赋值了。
3.value其实就是存放实际值的变量,它被volatile 关键字修饰,说明对于其他线程是可见的。
下面是它的构造器

  1. /**
  2. * Creates a new AtomicInteger with the given initial value.
  3. *
  4. * @param initialValue the initial value
  5. */
  6. //携带指定值的构造器
  7. public AtomicInteger(int initialValue) {
  8. value = initialValue;
  9. }
  10. /**
  11. * Creates a new AtomicInteger with initial value {@code 0}.
  12. */
  13. //默认构造器,默认值设置为0
  14. public AtomicInteger() {
  15. }

还有它的常用方法
1.自增
可以看到自增方法通过无限循环不停的尝试修改它的值,直到成功为止
首先获取当前值
然后自增 1
利用原子操作去设定想要的值,如果成功则返回自增后的值,否则继续循环

  1. /**
  2. * Atomically increments by one the current value.
  3. *
  4. * @return the updated value
  5. */
  6. public final int incrementAndGet() {
  7. //尝试去修改,直到成功为止
  8. for (;;) {
  9. int current = get();
  10. int next = current + 1;
  11. if (compareAndSet(current, next))
  12. //返回自增后的值
  13. return next;
  14. }
  15. }
  16. /**
  17. * Atomically increments by one the current value.
  18. *
  19. * @return the previous value
  20. */
  21. public final int getAndIncrement() {
  22. for (;;) {
  23. int current = get();
  24. int next = current + 1;
  25. if (compareAndSet(current, next))
  26. //返回自增前的值
  27. return current;
  28. }
  29. }

同上方法去不断尝试减一

  1. /**
  2. * Atomically decrements by one the current value.
  3. *
  4. * @return the updated value
  5. */
  6. public final int decrementAndGet() {
  7. //尝试去修改,直到成功为止
  8. for (;;) {
  9. int current = get();
  10. int next = current - 1;
  11. if (compareAndSet(current, next))
  12. //返回自减后的值
  13. return next;
  14. }
  15. }
  16. /**
  17. * Atomically decrements by one the current value.
  18. *
  19. * @return the previous value
  20. */
  21. public final int getAndDecrement() {
  22. for (;;) {
  23. int current = get();
  24. int next = current - 1;
  25. if (compareAndSet(current, next))
  26. //返回自减前的值
  27. return current;
  28. }
  29. }

由于是原子操作的,实例值又是线程修改可见的,所以是线程安全的

 

转载于:https://www.cnblogs.com/timoSkill/p/7448588.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值