我想做的是在一个线程内修改全局 ArrayList,并在我的线程外修改这个 ArrayList。
这是我的代码,它可以工作,但是当我从外部读取我的 ArrayList 时,它的大小正确,但此 ArrayList 中的所有元素都是最后添加的,我的意思是如果最后一个元素具有 pollingCode、pollingType、polling Value = 0 ,数组中的所有元素都具有相同的值。
有人知道为什么会这样吗?
public abstract class OverlayView extends RelativeLayout {
protected ArrayList<InputEvent> eventList = new ArrayList<InputEvent>();
public void StartEventMonitor() {
Thread b = new Thread(new Runnable() {
public void run() {
InputEvent ie= new InputEvent();
while (m_bMonitorOn) {
for (InputDevice idev:events.m_Devs) {
// Open more devices to see their messages
int pollingEvent = idev.getPollingEvent();
int pollingType=idev.getSuccessfulPollingType();
int pollingCode=idev.getSuccessfulPollingCode();
int pollingValue=idev.getSuccessfulPollingValue();
final String line =/* idev.getName()+
": " +*/ idev.getSuccessfulPollingType()+
" " + idev.getSuccessfulPollingCode() +
" " + idev.getSuccessfulPollingValue() +
"\n";
Log.d(LT, "Event:"+line);
ie.setCode(pollingCode);
ie.setType(pollingType);
ie.setValue(pollingValue);
eventList.add(ie);
}
}
}
}
});
b.start();
}
最佳答案
仅供引用,这与多线程无关。
您正在重复使用同一个 InputEvent 对象。因此,您调用 setCode
就是在调用同一 InputEvent 的 setCode 方法。添加只会每次添加相同的 IE 实例。
例如,尝试(假设列表大小 > 1)
if(eventList.get(0) == eventList.get(1)){
//re using the same object
}
您应该将 InputEvent 的创建赋值移动到 for 循环中。
关于java - 从线程修改全局 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480128/