AtomicReference 用以支持对象的原子操作:AtomicReference<V> 可以封装引用一个V实例,通过可以支持并发访问,set的时候进行对比判断,如果当前值和操作之前一样则返回false,否则表示数据没有 变化,例如下面的代码
- public final boolean compareAndSet(V expect, V update)
使用 AtomicReference 实现了并发计数:
- package test;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.atomic.AtomicReference;
- public class TS {
- public static void main(String[] args) throws InterruptedException {
- dfasd111();
- }
- private static AtomicReference<Integer> ar = new AtomicReference<Integer>(0);
- public static void dfasd111() throws InterruptedException {
- int t = 100;
- final int c = 100;
- final CountDownLatch latch = new CountDownLatch(t);
- for (int i = 0; i < t; i++) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- for (int i = 0; i < c; i++) {
- while (true) {
- Integer temp = ar.get();
- if (ar.compareAndSet(temp, temp + 1)) {
- break;
- }
- }
- }
- latch.countDown();
- }
- }).start();
- }
- latch.await();
- System.out.println(ar.get()); //10000000
- }
- public final void test() {
- System.out.println(this.getClass());
- }
- }
一、原子量实现的计数器
联系客服