java.util.concurrent.atomic.*包的体会

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;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值