我有兩個線程都需要訪問一個ArrayList<short[]>
實例變量。如何在訪問java ArrayList時阻止兩個線程發生衝突?
一個線程會異步通過回調添加short[]
項目添加到列表時,新的數據已經到達:void dataChanged(short[] theData)
另一個線程會定期檢查列表中有項目,如果這樣做,是怎麼回事遍歷所有項目,處理它們,並將它們從數組中移除。
如何設置這個以防止兩個線程之間發生衝突?
這做作代碼示例目前拋出一個java.util.ConcurrentModificationException
//instance vairbales
private ArrayList<short[]> list = new ArrayList<short[]>();
//asynchronous callback happening on the thread that adds the data to the list
void dataChanged(short[] theData) {
list.add(theData);
}
//thread that iterates over the list and processes the current data it contains
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
for(short[] item : list) {
//process the data
}
//clear the list to discared of data which has been processed.
list.clear();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
+1這就是要走的路! – assylias
+1正確的方法來設計解決方案 – Stephan