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