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

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



    下面是:

      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的实际用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-10 22:08