AtomicInteger的使用,多线程叠加或叠减

来源:互联网 发布:php会员积分管理系统 编辑:程序博客网 时间:2024/06/03 16:38
在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口
import java.util.concurrent.atomic.AtomicInteger;public class AtomicIntegerTest {public AtomicInteger inc = new AtomicInteger();public void increase() {inc.getAndIncrement();//i++操作//inc.getAndDecrement();//i--操作}public static void main(String[] args) {final AtomicIntegerTest test = new AtomicIntegerTest();for (int i = 0; i < 10; i++) {new Thread() {public void run() {for (int j = 0; j < 1000; j++)test.increase();};}.start();}while (Thread.activeCount() > 1)// 保证前面的线程都执行完Thread.yield();System.out.println(test.inc);}}

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

值得一看。

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

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

// setup to use Unsafe.compareAndSwapInt for updates  private static final Unsafe unsafe = Unsafe.getUnsafe();  private static final long valueOffset;  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方法,实现高效的硬件级别CASreturn unsafe.compareAndSwapInt(this, valueOffset, expect, update);}

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

0 0
原创粉丝点击