简体   繁体   English

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

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

I have a long running loop. 我的循环很长。

Inside the loop I have another loop to iterate (using iterator) on a arrayList. 在循环内部,我有另一个循环可以迭代(使用迭代器)arrayList。

If a condition is met while looping through array list I initiate a thread while passing it the current array list item and also the current iterator. 如果在遍历数组列表时满足条件,则在向其传递当前数组列表项以及当前迭代器的同时启动线程。

Some example code: 一些示例代码:

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 
}

If a condition is met in the UpdateThread , I want to remove the item from the testList like so: 如果在UpdateThread中满足条件,我想从testList中删除该项目, 如下所示:

this.itr.remove();

I have another long running loop (in another separate thread) concurrently and its doing similar types of processing on the array List (read, write etc...). 我同时有另一个长时间运行的循环(在另一个单独的线程中),并且它对数组List进行类似类型的处理(读,写等)。

My question is if in this other loop I'm iterating the testList will this reflect the changes from the other loop? 我的问题是,如果在另一个循环中我要迭代testList,是否会反映另一个循环的更改?

(In case you're wondering why I'm using thread for sync, this is for remote resource and database interaction, and I need this loop to be constant and instantaneous without wait time). (如果您想知道为什么我要使用线程进行同步,这是用于远程资源和数据库交互,并且我需要此循环是恒定且瞬时的,而无需等待时间)。

Why don't you use something like: 您为什么不使用类似以下的内容:

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();
        }; 

    };
};

//the UpdateThread class has a consructor UpdateThread(Test test, Iterator itr). // UpdateThread类具有构造函数UpdateThread(Test test,Iterator itr)。 so just modify it for fitting this example, or post it i think ki can do it for you. 因此,只需对其进行修改以适合该示例,或者发布它,我认为Ki可以为您完成。

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

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