Java NIO -AtomicInteger
来源:互联网 发布:java桌面开发框架 编辑:程序博客网 时间:2024/05/22 00:31
概述
通常情况下,在Java中我们对++i,--i的操作都是非线程安全的。对于一个++i存在三个独立的操作,获取变量i当前的值,为该值+1。如下代码,多线程操作i++。
public class UnsafeI {
public static int num = 0;
public static void main(String[] args) throws InterruptedException {
final int threadSize = 10000;
Thread[] ts = new Thread[threadSize];
for (int i = 0; i < threadSize; i++) {
ts[i] = new Thread() {
public void run() {
num++;
}
};
}
for (Thread t : ts) {
t.start();
}
System.out.println(num);
}
}
多次运行,在可能的情况下,我们会看到输出的num存在不同的值。
AtomicInteger提供一系列的线程安全的方法,供我们实现i++操作。
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
底层通过Unsafe方法实现。具体Unsafe的各个防范,有兴趣的可以参考如下博客,写的比较详细:http://ifeve.com/sun-misc-unsafe/
我们多线程环境对AtomicInteger进行操作。
import java.util.concurrent.atomic.AtomicInteger;
public class SafeAtomicInteger {
static final AtomicInteger value = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
final int threadSize = 10000;
Thread[] ts = new Thread[threadSize];
for (int i = 0; i < threadSize; i++) {
ts[i] = new Thread() {
public void run() {
value.incrementAndGet();
}
};
}
for (Thread t : ts) {
t.start();
}
System.out.println(value.get());
}
}
参考列表:http://www.blogjava.net/xylz/archive/2010/07/01/324988.html
http://ifeve.com/sun-misc-unsafe/
0 0
- Java NIO -AtomicInteger
- Java AtomicInteger
- java AtomicInteger
- Java AtomicInteger
- Java AtomicInteger
- Java AtomicInteger
- java AtomicInteger 类学习
- java 原子变量AtomicInteger
- 【Java多线程】AtomicInteger使用
- Java:AtomicInteger简介
- [Java]初识AtomicInteger
- Java基础之AtomicInteger
- Java AtomicInteger源码分析
- Java AtomicInteger 类
- 分析Java AtomicInteger
- java concurrent-AtomicInteger
- Volatile、AtomicInteger、java并发
- Java AtomicInteger(转载)
- java热加载技术hotswap
- 软件设计
- 1142: 【C语言训练】立方和不等式
- 第六周项目一-分数类的雏形(1)
- PHPExcel导出
- Java NIO -AtomicInteger
- ViewPager
- achartengine/MPAndroidChart——图表实现之Java
- 例程1. LKB -- 慕司板IAP15
- 1.Mysql数据库的优化技术(1)
- HDOJ 1202 The calculation of GPA
- linux yum命令详解
- Codeforces Round #346 (Div. 2) B (pair+vector的应用)
- Mac下使用git和github