JAVA在java.util.concurrent中提供了对原子操作的包,用来实现一些原子操作。
package com.zhuyang.concurrency.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest extends Thread {
private static AtomicInteger num = new AtomicInteger();
public void run() {
System.out.println(Thread.currentThread());
AtomicIntegerTest.num.incrementAndGet();//每个线程对num进行+1
}
public static void main(String[] args) {
for (int i = 0; i < 6600; i++) {
AtomicIntegerTest t = new AtomicIntegerTest();
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("after loop, AtomicInteger value is " + num);
}
}
after loop, AtomicInteger value is 6600
源码分析
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))//如果预期得到的结果和更新后的结果相等,则直接返回。否则返回当前值
return next;
}
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* compareAndSet使用Unsafe调用native本地方法CAS(CompareAndSet)递增数值。
* 判断预期得到的结果是否和更新后的结果是否相等
* @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);
}