Java:有没有AtomicFloat或AtomicDouble? [英] Java: is there no AtomicFloat or AtomicDouble?

查看:3274
本文介绍了Java:有没有AtomicFloat或AtomicDouble?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到 AtomicInteger AtomicLong ,但其中 AtomicFloat (或 AtomicDouble )?也许有一些技巧?

I have found AtomicInteger, AtomicLong, but where is AtomicFloat (or AtomicDouble)? Maybe there is some trick?

推荐答案

java.util.concurrent 说明以下内容:

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 using Float.floatToIntBits and Float.intBitstoFloat conversions, and doubles using Double.doubleToLongBits and Double.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屋!

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