考虑以下类: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; }}我可以采取哪些预防措施来确保此类在多线程方面没有任何问题。有良好的表现。同时确保货币精度不会成为问题
3 回答
郎朗坤
TA贡献1921条经验 获得超9个赞
使 POJO(Plain Old Java Object)线程安全有几个关键点:
使类不可变。如果添加任何实例变量,请将它们设为 final 或 volatile。
使您的 getter 和 setter 同步,即
public synchronized void setAmount(double amount) {}
饮歌长啸
TA贡献1951条经验 获得超3个赞
艾哈迈德,你的问题是模棱两可的。
关于多线程:不清楚您所说的多线程问题是什么意思。例如,该类在多线程方面没有任何问题,因为它是同步良好的,但是您仍然可以将 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;
}
}
添加回答
举报
0/150
提交
取消