考虑以下类:
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;
}
}
我可以采取哪些预防措施来确保此类在多线程方面没有任何问题。有良好的表现。同时确保货币精度不会出现问题
最佳答案
艾哈迈德,你的问题很模糊。
关于多线程:不清楚您所说的多线程问题是什么意思。例如,该类在同步良好的意义上没有任何多线程问题,但您仍然可以将 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;
}
}
关于货币精度:正如 Andreas 回答的那样,请参阅:Why not use Double or Float to represent currency? 。另外,这个可能很有趣:What is the best data type to use for money in Java app?
关于java - 多线程、性能和精度考虑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522864/