查看 netbeans affable bean 教程。为什么我们需要在这里使用同步方法?
public synchronized int getNumberOfItems() {
numberOfItems = 0;
for (ShoppingCartItem scItem : items) {
numberOfItems += scItem.getQuantity();
}
return numberOfItems;
}
public synchronized double getSubtotal() {
double amount = 0;
for (ShoppingCartItem scItem : items) {
Product product = (Product) scItem.getProduct();
amount += (scItem.getQuantity() * product.getPrice().doubleValue());
}
return amount;
}
最佳答案
看起来与 ShoppingCartItems 管理相关的每个方法都是同步的。当然是为了防止并发访问 items 列表 ( List<ShoppingCartItem> items;
)。
如果没有同步,您可能有 1+ 个线程访问“读取”方法,例如 getSubtotal ()
而items
名单正在公开更新中synchronized void addItem(Product product)
由另一个线程。
来源可以找到here
关于java - affable bean 购物车中同步方法的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9884148/