AtomicInteger的使用,多线程叠加或叠减
来源:互联网 发布:php会员积分管理系统 编辑:程序博客网 时间:2024/06/03 16:38
在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口
好了,看到这个代码,基本上就看到这个类的核心了。相对来说,其实这个类还是比较简单的。可以参考http://hittyt.iteye.com/blog/1130990
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
- 多线程1:AtomicInteger的使用,多线程叠加或叠减
- AtomicInteger的使用,多线程叠加或叠减
- 多线程之AtomicInteger的使用
- 【Java多线程】AtomicInteger使用
- AtomicInteger原子的使用
- AtomicInteger的使用
- AtomicInteger的使用
- 无锁类的使用---AtomicInteger
- AtomicInteger的介绍和使用
- AtomicInteger的介绍和使用
- Java中AtomicInteger的使用!!!
- AtomicInteger的介绍和使用
- AtomicInteger的认识与使用
- Java的多线程编程模型之AtomicInteger
- AtomicInteger使用
- AtomicInteger 使用
- AtomicInteger使用
- 多线程编程4------面试题使用资源互斥类AtomicInteger
- 友盟推送使用别名(Alias)推送到具体用户
- shouldRasterize
- java process的waitfor()阻塞问题
- JPUSH服务端集成(JAVA版本)
- Zen Coding: 一种快速编写HTML/CSS代码的方法(已经更名为emmet)
- AtomicInteger的使用,多线程叠加或叠减
- 服务器端编程心得(二)—— Reactor模式
- CXF系列之WSDL文件结构
- MySQL的外键约束:Cascade/Restrict/No action/SET NULL :级联操作
- 时间戳
- java反射机制学习笔记
- <Retrofit2> 添加header和baseparam
- 基于Solr的HBase多条件查询测试
- 常用centos命令