Java并发AtomicBoolean类

简介java.util.concurrent.atomic.AtomicBoolean类提供了可以原子读取和写入的底层布尔值的操作,并且还包含高级原子操作。 AtomicBoolean支持基础布尔变量上的原子操作。 它具有获取和设置方法,如在volatile变量上的读取和写入。 也就是说,一个集合与同一变量上的任何后续get相关联。 原子compareAndSet方法也具有这些内存一致性功能。
方法:摘自jdk1.8
Java并发AtomicBoolean类_第1张图片
示例
以下AtomicBooleanTest程序显示了基于线程的环境中AtomicBoolean变量的使用。

import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanTest {
	public static void main(String[] args) {
		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();
	}
}

结果:Java并发AtomicBoolean类_第2张图片

你可能感兴趣的:(java并发编程)