我想設計一個轉換的流程圖爲Java或任何其他代碼的軟件。然而,我一再得到ConcurrentModificationException .. 但我不能使用布爾值來防止concurrentModification,因爲訪問鏈表發生在各個地方。ConcurrentModificationException的在LinkedList的
因此,作爲一個解決方案,我創建了以下適配器類。但是它也會從下一個方法拋出相同的異常。是否有任何其他的解決方案,或者如果可以,PLZ讓我知道如何修改我的代碼...
非常感謝你......
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListAdapter<T> extends LinkedList<T>{
@Override
public boolean add(T t){
boolean b;
synchronized(this){
b = super.add(t);
}
return b;
}
@Override
public T remove(){
T t;
synchronized(this){
t = super.remove();
}
return t;
}
@Override
public Iterator<T> iterator(){
final LinkedListAdapter<T> adap = this;
return
new Iterator<T>(){
private Iterator<T> iter;
{
synchronized(adap){
iter = LinkedListAdapter.this.getIterator();
}
}
@Override
public boolean hasNext() {
boolean b;
synchronized(adap){
b = iter.hasNext();
}
return b;
}
@Override
public T next() {
T t;
synchronized(adap){
t = iter.next();
}
return t;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
protected Iterator<T> getIterator() {
Iterator<T> iter;
synchronized(this){
iter = super.iterator();
}
return iter;
}
}
@SLaks必須是對SO有史以來最有幫助的評論「一旦你解決這個問題,將工作」。 – josefx
@josefx:我的觀點是他的問題是完全向後解決問題。 – SLaks
是的。這是正確的。在設計軟件時,我並沒有預料到任何多線程問題,因爲我使用了單線程。但是,使用paintComponent時會出現意外的多線程問題。然後作爲解決方案,我嘗試使用適配器。非常感謝 – maamaa