编辑:这不是重复。链接的另一个问题是询问如何在迭代时删除元素而不是获取CME异常,在我的问题中我不想同时迭代和删除元素。事实上,我想确保不会发生这种情况。
我在尝试通过矢量theSpace进行迭代时遇到并发修改错误,我所有影响它的方法都是同步的,所以我不明白导致异常的原因是什么? (对不起java的新杂乱代码)
public class TupleSpace implements aTupleSpace {
private Collection<aTuple> theSpace;
public TupleSpace() {
theSpace = new Vector<aTuple>();
}
public synchronized void out(aTuple v) {
theSpace.add(v);
notifyAll();
}
public synchronized void in(aTemplate t, aMonoVariable<aTuple> result) {
while (true) {
for (aTuple tup : theSpace) {
if (t.matches(tup)) {
result.becomes(tup);
theSpace.remove(tup);
return;
}
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public synchronized void rd(aTemplate t, aMonoVariable<aTuple> result) {
while (true) {
for (aTuple tup : theSpace) {
if (t.matches(tup)) {
result.becomes(tup);
return;
}
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
========== .matches和.nth(帮助者)的代码==========
public boolean matches(aTuple t) {
if(this.elements.size() == t.length() ){
for (int i=0; i<t.length(); i++) {
if (!(this.nth(i).equals( t.nth(i)))){return false;}
}
return true;
}return false;
}
public TypedValue nth(int n) {
if( n < 0 || n >= elements.size()) return null;
else return elements.get(n);