AtomicInteger的实际用法 [英] Practical uses for AtomicInteger

查看:167
本文介绍了AtomicInteger的实际用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解AtomicInteger和其他Atomic变量允许并发访问。 AtomicInteger code>:




  • 作为原子计数器( incrementAndGet()


  • 作为支持 compare-and-swap 指令( compareAndSet())来实现非阻塞算法。



    下面是 Brian的非阻塞随机数生成器示例Göetz的Java并发实践

      public class AtomicPseudoRandom extends PseudoRandom {
    private AtomicInteger seed;
    AtomicPseudoRandom(int seed){
    this.seed = new AtomicInteger(seed);
    }

    public int nextInt(int n){
    while(true){
    int s = seed.get();
    int nextSeed = calculateNext(s);
    if(seed.compareAndSet(s,nextSeed)){
    int remainder = s%n;
    return remaining> 0?余数:余数+ n;
    }
    }
    }
    ...
    }


    b $ b

    可以看到,它基本上与 incrementAndGet()几乎相同,但执行任意计算( calculateNext



I sort of understand that AtomicInteger and other Atomic variables allow concurrent accesses. In what cases is this class typically used though?

解决方案

There are two main uses of AtomicInteger:

  • As an atomic counter (incrementAndGet(), etc) that can be used by many threads concurrently

  • As a primitive that supports compare-and-swap instruction (compareAndSet()) to implement non-blocking algorithms.

    Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:

    public class AtomicPseudoRandom extends PseudoRandom {
        private AtomicInteger seed;
        AtomicPseudoRandom(int seed) {
            this.seed = new AtomicInteger(seed);
        }
    
        public int nextInt(int n) {
            while (true) {
                int s = seed.get();
                int nextSeed = calculateNext(s);
                if (seed.compareAndSet(s, nextSeed)) {
                    int remainder = s % n;
                    return remainder > 0 ? remainder : remainder + n;
                }
            }
        }
        ...
    }
    

    As you can see, it basically works almost the same way as incrementAndGet(), but performs arbitrary calculation (calculateNext()) instead of increment (and processes the result before return).

这篇关于AtomicInteger的实际用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆