问题描述
用于AtomicBoolean状态的Oracle JDK Javadoc:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html
我和一位同事试图找出一个用例,其中AtomicBoolean不能替代,并且我们唯一能想到的是,布尔对象具有某些方法,而AtomicBoolean没有. >
这是唯一的原因,还是在撰写时还有其他想法?
Boolean
是原始boolean
周围的包装器类.它可以由编译器从boolean
自动创建(装箱转换),也可以转换为布尔值(拆箱转换). AtomicBoolean
并非如此,因为它是一个为并发目的而设计的单独类.
因此,这两个类在语言级别上具有不同的语义:
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
The Oracle JDK Javadoc for AtomicBoolean states:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html
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
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!