为什么 AtomicBoolean 不能替代 Boolean? [英] Why can't AtomicBoolean be a replacement for Boolean?

查看:61
本文介绍了为什么 AtomicBoolean 不能替代 Boolean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AtomicBoolean 状态的 Oracle JDK Javadoc:

The Oracle JDK Javadoc for AtomicBoolean states:

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html

一个可以自动更新的布尔值.见用于描述的 java.util.concurrent.atomic 包规范原子变量的属性.AtomicBoolean 用于诸如原子更新标志之类的应用程序,并且不能用作替换布尔值.

A boolean value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicBoolean is used in applications such as atomically updated flags, and cannot be used as a replacement for a Boolean.

我和一位同事试图找出 AtomicBoolean 不能替代的用例,我们唯一能想到的是 Boolean 对象有一些 AtomicBoolean 没有的方法.

A colleague and I were trying to figure out a use-case where the AtomicBoolean can't be a substitute and the only thing we can think of is that there are methods the Boolean object has that the AtomicBoolean does not.

这是唯一的原因还是在写的时候有其他想法?

Is that the only reason or was there something else in mind when that was written?

推荐答案

Boolean 是原始 boolean 的包装类.它可以由编译器从 boolean 自动创建(装箱转换)或转换为布尔值(拆箱转换).AtomicBoolean 不是这种情况,它是为并发目的而设计的单独类.

Boolean is the wrapper class around the primitive boolean. It may be automatically created from a boolean by the compiler (boxing conversion) or converted to a boolean (unboxing conversion). This is not the case for AtomicBoolean where it is a separate class designed for concurrency purposes.

因此这两个类在语言级别具有不同的语义:

Hence the two classes have different semantics at the language level:

Boolean b = new Boolean(true);
AtomicBoolean ab = new AtomicBoolean(true);
System.out.println(true == b);  // automatic unboxing of Boolean variable
System.out.println(true == ab);  // compiler error

这篇关于为什么 AtomicBoolean 不能替代 Boolean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆