Java:没有 AtomicFloat 或 AtomicDouble 吗? [英] Java: is there no AtomicFloat or AtomicDouble?
问题描述
我找到了AtomicInteger
、AtomicLong
,但是AtomicFloat
(或AtomicDouble
)在哪里?也许有什么技巧?
I have found AtomicInteger
, AtomicLong
, but where is AtomicFloat
(or AtomicDouble
)? Maybe there is some trick?
推荐答案
java.util.concurrent
package 声明如下:
The API docs for the java.util.concurrent
package states the following:
[...] 此外,只为那些在预期应用程序中通常有用的类型提供类.例如,没有用于表示字节的原子类.在您希望这样做的罕见情况下,您可以使用 AtomicInteger
来保存字节值,并进行适当的转换.您还可以使用 Float.floatToIntBits
和 Float.intBitstoFloat
转换保存浮点数,使用 Double.doubleToLongBits
和 Double.longBitsToDouble
转换.
[...] Additionally, classes are provided only for those types that are commonly useful in intended applications. For example, there is no atomic class for representing byte. In those infrequent cases where you would like to do so, you can use an
AtomicInteger
to hold byte values, and cast appropriately. You can also hold floats usingFloat.floatToIntBits
andFloat.intBitstoFloat
conversions, and doubles usingDouble.doubleToLongBits
andDouble.longBitsToDouble
conversions.
我并不是说这是一个方便的解决方案,但这似乎是一种解释.我想你可能想要包装一个 AtomicInteger
并为 getFloat
/setFloat
等提供访问方法.
I'm not claiming it's a convenient solution, but that seems to be the explanation. I suppose you would probably want to wrap an AtomicInteger
and provide access methods for getFloat
/ setFloat
etc.
我实际上是在写一个.给你:
I actually got around writing one. Here you go:
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.Float.*;
class AtomicFloat extends Number {
private AtomicInteger bits;
public AtomicFloat() {
this(0f);
}
public AtomicFloat(float initialValue) {
bits = new AtomicInteger(floatToIntBits(initialValue));
}
public final boolean compareAndSet(float expect, float update) {
return bits.compareAndSet(floatToIntBits(expect),
floatToIntBits(update));
}
public final void set(float newValue) {
bits.set(floatToIntBits(newValue));
}
public final float get() {
return intBitsToFloat(bits.get());
}
public float floatValue() {
return get();
}
public final float getAndSet(float newValue) {
return intBitsToFloat(bits.getAndSet(floatToIntBits(newValue)));
}
public final boolean weakCompareAndSet(float expect, float update) {
return bits.weakCompareAndSet(floatToIntBits(expect),
floatToIntBits(update));
}
public double doubleValue() { return (double) floatValue(); }
public int intValue() { return (int) get(); }
public long longValue() { return (long) get(); }
}
这篇关于Java:没有 AtomicFloat 或 AtomicDouble 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!