Java并发 专题
您的位置:java > Java并发专题 > Java并发AtomicBoolean类
Java并发AtomicBoolean类
作者:--    发布时间:2019-11-20

java.util.concurrent.atomic.atomicboolean类提供了可以原子读取和写入的底层布尔值的操作,并且还包含高级原子操作。 atomicboolean支持基础布尔变量上的原子操作。 它具有获取和设置方法,如在volatile变量上的读取和写入。 也就是说,一个集合与同一变量上的任何后续get相关联。 原子compareandset方法也具有这些内存一致性功能。

atomicboolean类中的方法

以下是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!

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册