java中关于AtomicInteger的使用

在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。咳哟参考我之前写的一篇博客http://www.cnblogs.com/sharkli/p/5597148.html,今天偶然发现可以不用synchronized使用AtomicInteger完成同样的功能,具体代码如下,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package  TestAtomicInteger;
 
import  java.util.concurrent.atomic.AtomicInteger;
 
class  MyThread  implements  Runnable {
//    static  int i = 0;
      static  AtomicInteger ai= new  AtomicInteger( 0 );
      
 
     public  void  run() {
         for  ( int  m =  0 ; m <  1000000 ; m++) {
             ai.getAndIncrement();
         }
     }
};
 
public  class  TestAtomicInteger {
     public  static  void  main(String[] args)  throws  InterruptedException {
         MyThread mt =  new  MyThread();
 
         Thread t1 =  new  Thread(mt);
         Thread t2 =  new  Thread(mt);
         t1.start();
         t2.start();
         Thread.sleep( 500 );
         System.out.println(MyThread.ai.get());
     }
}

  可以发现结果都是2000000,也就是说AtomicInteger是线程安全的。

值得一看。

这里,我们来看看AtomicInteger是如何使用非阻塞算法来实现并发控制的。

AtomicInteger的关键域只有一下3个:

Java代码   收藏代码
  1. // setup to use Unsafe.compareAndSwapInt for updates  
  2. private static final Unsafe unsafe = Unsafe.getUnsafe();  
  3. private static final long valueOffset;  
  4. private volatile int value;  

 这里, unsafe是java提供的获得对对象内存地址访问的类,注释已经清楚的写出了,它的作用就是在更新操作时提供“比较并替换”的作用。实际上就是AtomicInteger中的一个工具。

valueOffset是用来记录value本身在内存的编译地址的,这个记录,也主要是为了在更新操作在内存中找到value的位置,方便比较。

注意:value是用来存储整数的时间变量,这里被声明为volatile,就是为了保证在更新操作时,当前线程可以拿到value最新的值(并发环境下,value可能已经被其他线程更新了)。

这里,我们以自增的代码为例,可以看到这个并发控制的核心算法:

/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
//这里可以拿到value的最新值
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}

public final boolean compareAndSet(int expect, int update) {
//使用unsafe的native方法,实现高效的硬件级别CAS
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

 

 好了,看到这个代码,基本上就看到这个类的核心了。相对来说,其实这个类还是比较简单的。可以参考http://hittyt.iteye.com/blog/1130990

from: https://www.cnblogs.com/sharkli/p/5623524.html

猜你喜欢

转载自www.cnblogs.com/GarfieldEr007/p/10225677.html
今日推荐