java.util.concurrent.atomic.AtomicLong
類提供了可以被原子地讀取和寫入的底層long
值的操作,並且還包含高階原子操作。 AtomicLong
支援基礎long
型別變數上的原子操作。 它具有獲取和設定方法,如在volatile
變數上的讀取和寫入。 也就是說,一個集合與同一變數上的任何後續get
相關聯。 原子compareAndSet
方法也具有這些記憶體一致性功能。
以下是AtomicLong
類中可用的重要方法的列表。
序號 | 方法 | 描述 |
---|---|---|
1 | public long addAndGet(long delta) |
將給定值原子地新增到當前值。 |
2 | public boolean compareAndSet(long expect, long update) |
如果當前值與預期值相同,則將該值原子設定為給定的更新值。 |
3 | public long decrementAndGet() |
當前值原子減1 。 |
4 | public double doubleValue() |
以double 形式返回指定數位的值。 |
5 | public float floatValue() |
以float 形式返回指定數位的值。 |
6 | public long get() |
獲取當前值。 |
7 | public long getAndAdd(long delta) |
自動將給定值新增到當前值。 |
8 | public long getAndDecrement() |
當前值原子減1 。 |
9 | public long getAndIncrement() |
當前值原子增加1 。 |
10 | public long getAndSet(long newValue) |
將原子設定為給定值並返回舊值。 |
11 | public long incrementAndGet() |
原子上增加一個當前值。 |
12 | public int intValue() |
以int 形式返回指定數位的值。 |
13 | public void lazySet(long newValue) |
最終設定為給定值。 |
14 | public long longValue() |
返回指定數位的值為long 型別。 |
15 | public void set(long newValue) |
設定為給定值。 |
16 | public String toString() |
返回當前值的String 表示形式。 |
17 | public boolean weakCompareAndSet(long expect, long update) |
如果當前值與預期值相同,則將該值原子設定為給定的更新值。 |
以下TestThread
程式顯示了在基於執行緒的環境中使用AtomicLong
的計數器的安全實現。
import java.util.concurrent.atomic.AtomicLong;
public class TestThread {
static class Counter {
private AtomicLong c = new AtomicLong(0);
public void increment() {
c.getAndIncrement();
}
public long 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