我有两个线程都需要访问ArrayList<short[]>
实例变量。
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();
}
}
}
});