目录

并发 - AtomicInteger( AtomicInteger)

java.util.concurrent.atomic.AtomicInteger类提供对底层int值的操作,可以原子方式读取和写入,还包含高级原子操作。 AtomicInteger支持底层int变量的原子操作。 它具有get和set方法,类似于对volatile变量的读写操作。 也就是说,集合与同一变量上的任何后续获取具有先发生关系。 原子compareAndSet方法也具有这些内存一致性功能。

AtomicInteger方法

以下是AtomicInteger类中可用的重要方法列表。

Sr.No. 方法和描述
1

public int addAndGet(int delta)

以原子方式将给定值添加到当前值。

2

public boolean compareAndSet(int expect, int update)

如果当前值与预期值相同,则以原子方式将值设置为给定的更新值。

3

public int decrementAndGet()

原子地减去当前值的一个。

4

public double doubleValue()

以double形式返回指定数字的值。

5

public float floatValue()

以float形式返回指定数字的值。

6

public int get()

获取当前值。

7

public int getAndAdd(int delta)

原子地将给定值添加到当前值。

8

public int getAndDecrement()

原子地减去当前值的一个。

9

public int getAndIncrement()

原子地将当前值增加1。

10

public int getAndSet(int newValue)

原子设置为给定值并返回旧值。

11

public int incrementAndGet()

原子地将当前值增加1。

12

public int intValue()

以int形式返回指定数字的值。

13

public void lazySet(int newValue)

最终设置为给定值。

14

public long longValue()

以long形式返回指定数字的值。

15

public void set(int newValue)

设置为给定值。

16

public String toString()

返回当前值的String表示形式。

17

public boolean weakCompareAndSet(int expect, int update)

如果当前值与预期值相同,则以原子方式将值设置为给定的更新值。

例子 (Example)

以下TestThread程序在基于线程的环境中显示计数器的不安全实现。

public class TestThread {
   static class Counter {
      private int c = 0;
      public void increment() {
         c++;
      }
      public int value() {
         return c;
      }
   }
   public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();
      //1000 threads
      for(int i = 0; i < 1000 ; i++) {
         new Thread(new Runnable() {
            public void run() {
               counter.increment();
            }
         }).start(); 
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
   }  
}

根据计算机的速度和线程交错,这可能会产生以下结果。

输出 (Output)

Final number (should be 1000): 1000

例子 (Example)

以下TestThread程序在基于线程的环境中使用AtomicInteger显示计数器的安全实现。

import java.util.concurrent.atomic.AtomicInteger;
public class TestThread {
   static class Counter {
      private AtomicInteger c = new AtomicInteger(0);
      public void increment() {
         c.getAndIncrement();
      }
      public int value() {
         return c.get();
      }
   }
   public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();
      //1000 threads
      for(int i = 0; i < 1000 ; i++) {
         new Thread(new Runnable() {
            public void run() {
               counter.increment();
            }
         }).start(); 
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
   }
}

这将产生以下结果。

输出 (Output)

Final number (should be 1000): 1000
↑回到顶部↑
WIKI教程 @2018