仅修改列表内的对象属性时获取ConcurrentModificationException

时间:2019-05-05 13:22:53

标签: java multithreading synchronized concurrentmodification

我正在尝试遍历两个不同线程中的ArrayList对象。

例如,假设列表中对象的类型为Bottle,而试图访问该列表的两个线程将为BuyerSeller

我正在尝试使用线程中的两种方法来更新Bottle对象。我没有从列表中添加或删除对象。 (两种方法均为staticsynchronized

BuyerSeller都有多个线程在运行。

我可能得到这个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
        }
    }
}

有什么好的方法可以避免这种情况?

0 个答案:

没有答案
相关问题