java.util.concurrent.atomic.*包的体会
package thread.concurrent.atomic;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import sun.misc.Unsafe;
public class AtomicTest {
AtomicLong atomicLong = new AtomicLong(11);
AtomicReference<Map> atomicRef = null;
// private static long value = 10;
// private static final Unsafe unsafe = Unsafe.getUnsafe();
public static void main(String[] args) throws SecurityException,
NoSuchFieldException {
final AtomicTest atomicLongTest = new AtomicTest();
atomicLongTest.set();
for (int i = 0; i < 10; i++) {
new Thread() {
public void run() {
atomicLongTest.updateRef();
};
}.start();
}
// Field valueField = AtomicLongTest.class.getDeclaredField("value");
// long ll = unsafe.objectFieldOffset(valueField);
// System.out.println(ll);
}
private void set() {
Map map = new HashMap();
map.put("name", "name1");
//通过AtomicReference封装的对象就是原子对象了。
atomicRef = new AtomicReference<Map>(map);
}
private Object updateRef() {
boolean f;
Map expect;
do {
expect = atomicRef.get();
Map update = new HashMap();
update.putAll(expect);
int n = (new Random()).nextInt(1000);
update.put("name", n);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
f = atomicRef.compareAndSet(expect, update);
System.out.println(Thread.currentThread().getName() + ",得到的原来的map:"
+ expect + ",新的map:" + update + ",f:" + f);
} while (!f);
return expect;
}
private long count() {
boolean f;
long r;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
do {
r = atomicLong.get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* AtomicLong这个类是提供原子操作的帮助类,其实没多少实质性的内容,这个类主要靠compareAndSet这个方,
* 而这个方法其实是调用sun.misc.Unsafe这个非安全类完成的。之所以说是非安全类是因为这个类会根据平台的不同调用
* 当前平台的本地API做事,这个包也是SUN唯一没有公开的包。 首先回去得到一个Unsafe unsafe =
* Unsafe.getUnsafe();的对象
* 然后调用unsafe.compareAndSwapLong(this,valueOffset, expect,
* update);方法完成任务的。
*
* 把value申明成volatile的,其他的方法可以随便写了。
*
*/
f = atomicLong.compareAndSet(r, r + 1);// 比较并且更新值,如果更新失败返回false,否则返回true
System.out.println(Thread.currentThread().getName() + ",r:" + r
+ ",f:" + f);
} while (!f);
return r;
}
}