java.util.concurrent.atomic.AtomicInteger类提供可以原子方式读取和写入的基础int值的操作,还包含高级原子操作. AtomicInteger支持底层int变量的原子操作.它具有get和set方法,类似于对volatile变量的读写操作.也就是说,一个集合与之前的相关变量的任何后续获取具有先发生关系.原子compareAndSet方法也具有这些内存一致性功能.
以下是AtomicInteger类中可用的重要方法列表.
Sr.No. | 方法&说明 |
---|---|
1 | public int addAndGet(int delta) 以原子方式将给定值添加到当前值. |
2 | public boolean compareAndSet(int expect,int update) 如果当前值与预期值相同,则以原子方式将值设置为给定的更新值. |
3 | public int decrementAndGet() 原子地将当前值减1. |
4 | public double doubleValue() 返回值指定的数字为双. |
5 | public float floatValue() 以float形式返回指定数字的值. |
6 | public int get() 获取当前值. |
7 | public int getAndAdd(int delta) Atomiclly将给定值添加到当前值. |
8 | public int getAndDecrement() 以原子方式将当前值减1. |
9 | public int getAndIncrement()
|
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) 以原子方式将值设置为t如果当前值与预期值相同,则给出更新值. |
以下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()); } }
根据计算机的速度和线程交错,这可能会产生以下结果.
Final number (should be 1000): 1000
以下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()); } }
这将产生以下结果.
Final number (should be 1000): 1000