多线程、性能和精度考虑

考虑以下类:


public class Money {

    private double amount;


    public Money(double amount) {

        super();

        this.amount = amount;

    }


    public double getAmount() {

        return amount;

    }


    public void setAmount(double amount) {

        this.amount = amount;

    }


    public Money multiplyBy( int factor) {

        this.amount *= factor;

        return this;

    }

}

我可以采取哪些预防措施来确保此类在多线程方面没有任何问题。有良好的表现。同时确保货币精度不会成为问题


哆啦的时光机
浏览 165回答 3
3回答

郎朗坤

使 POJO(Plain Old Java Object)线程安全有几个关键点:使类不可变。如果添加任何实例变量,请将它们设为 final 或 volatile。使您的 getter 和 setter 同步,即public synchronized void setAmount(double amount) {}

饮歌长啸

艾哈迈德,你的问题是模棱两可的。关于多线程:不清楚您所说的多线程问题是什么意思。例如,该类在多线程方面没有任何问题,因为它是同步良好的,但是您仍然可以将 Money 对象的状态设置为混乱,由多个线程使用它:public class Money {    private volatile double amount;    public Money(double amount) {        super();        this.amount = amount;    }    public double getAmount() {        return amount;    }    public synchronized void setAmount(double amount) {        this.amount = amount;    }    public synchronized Money multiplyBy( int factor) {        this.amount *= factor;        return this;    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java