Se *_*orm -1 java concurrency synchronization iterator
如何为此代码块获取ConcurrentModificationException?
synchronized (list) {
for (Iterator<?> it = list.iterator(); it.hasNext(); ) {
Object object = it.next();
// do something to object without touching list
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:对不起,这不够具体://对对象执行某些操作不会触及列表
例如,通过另一个线程修改列表.
仅仅因为您同步此代码块并不意味着阻止对列表的所有访问.它只确保列表上同步的所有其他块不能并行执行.
如果列表由多个线程共享,则必须在同一监视器上同步其所有用法.