繁体   English   中英

在Java中从单独的线程中的ArrayList中删除项目

[英]Removing an item from ArrayList in a separate Thread in Java

我的循环很长。

在循环内部,我有另一个循环可以迭代(使用迭代器)arrayList。

如果在遍历数组列表时满足条件,则在向其传递当前数组列表项以及当前迭代器的同时启动线程。

一些示例代码:

List<Test> testList = Collections.synchronizedList(new ArrayList<Test>());

//scanTests in a thread
while(scanTests) {
    for(Iterator<Test> itr = this.testList.iterator(); itr.hasNext();) {
        Test test = itr.next();
        if (test.closed == true && !test.inUpdateThread) {
            test.inUpdateThread = true;
            UpdateThread urt = new UpdateThread(test, itr);
            new Thread(urt).start();
        }
    }
}

//scanSomethingElse is in another thread
while (scanSomethingElse) {
    //manipulating testList 
}

如果在UpdateThread中满足条件,我想从testList中删除该项目, 如下所示:

this.itr.remove();

我同时有另一个长时间运行的循环(在另一个单独的线程中),并且它对数组List进行类似类型的处理(读,写等)。

我的问题是,如果在另一个循环中我要迭代testList,是否会反映另一个循环的更改?

(如果您想知道为什么我要使用线程进行同步,这是用于远程资源和数据库交互,并且我需要此循环是恒定且瞬时的,而无需等待时间)。

您为什么不使用类似以下的内容:

while (true) {
    for (int i = 0;i < testList.size(); i++) {
        Test test = testList.get(i);
        if (test.closed == true && !test.inUpdateThread) {
            test.inUpdateThread = true;
            UpdateThread urt = new UpdateThread(some other constructor here);
            new Thread(urt).start();
        }; 

    };
};

// UpdateThread类具有构造函数UpdateThread(Test test,Iterator itr)。 因此,只需对其进行修改以适合该示例,或者发布它,我认为Ki可以为您完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM