我正在尝试遍历两个不同线程中的ArrayList
对象。
例如,假设列表中对象的类型为Bottle
,而试图访问该列表的两个线程将为Buyer
和Seller
。
我正在尝试使用线程中的两种方法来更新Bottle对象。我没有从列表中添加或删除对象。 (两种方法均为static
和synchronized
)
Buyer
和Seller
都有多个线程在运行。
我可能得到这个exception
是因为Seller
线程之一正在尝试更新同一Bottle
对象,而买方线程之一正在更新该对象吗?
只是个更好的主意,列表和方法如下。
class Seller {
static synchronized void someMethod(List<Bottle> bottles) {
for (Bottle bottle:bottles)
{
//some code
bottle.updateAPropertyInsideBottleObject(newValue);
//more code
}
}
}
class Buyer {
static synchronized void someMethod(List<Bottle> bottles) {
for (Bottle bottle:bottles)
{
//some code
bottle.updateAPropertyInsideBottleObject(newValue);
//more code
}
}
}
有什么好的方法可以避免这种情况?