java.util.concurrent.atomic.atomicreference
类提供了可以原子读取和写入的底层对象引用的操作,还包含高级原子操作。 atomicreference
支持对底层对象引用变量的原子操作。 它具有获取和设置方法,如在易变的变量上的读取和写入。 也就是说,一个集合与同一变量上的任何后续get
相关联。 原子compareandset
方法也具有这些内存一致性功能。
以下是atomicreference
类中可用的重要方法的列表。
序号 | 方法 | 描述 |
---|---|---|
1 | public boolean compareandset(v expect, v update) |
如果当前值== 期望值,则将该值原子设置为给定的更新值。 |
2 | public boolean get() |
返回当前值。 |
3 | public boolean getandset(v newvalue) |
将原子设置为给定值并返回上一个值。 |
4 | public void lazyset(v newvalue) |
最终设定为给定值。 |
5 | public void set(v newvalue) |
无条件地设置为给定的值。 |
6 | public string tostring() |
|
7 | public boolean weakcompareandset(v expect, v update) |
如果当前值== 期望值,则将该值原子设置为给定的更新值。 |
以下testthread
程序显示了基于线程的环境中atomicreference
变量的使用。
import java.util.concurrent.atomic.atomicreference;
public class testthread {
private static string message = "hello";
private static atomicreference<string> atomicreference;
public static void main(final string[] arguments) throws interruptedexception {
atomicreference = new atomicreference<string>(message);
new thread("thread 1") {
public void run() {
atomicreference.compareandset(message, "thread 1");
message = message.concat("-thread 1!");
};
}.start();
system.out.println("message is: " + message);
system.out.println("atomic reference of message is: " + atomicreference.get());
}
}
这将产生以下结果 -
message is: hello
atomic reference of message is: thread 1