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