简体   繁体   English

如何确保在循环遍历列表后添加的Java并发列表中的元素得到正确处理?

[英]How to make sure elements of a concurrent list in java, that are added after the list has been looped through, are handled properly?

I have a concurrent list of objects. 我有一个并发对象列表。 Multiple threads add to this list. 多个线程添加到该列表。 At some point I loop through this list and perform operations on the list elements. 在某个时候,我遍历此列表并对列表元素执行操作。 How do I ensure that I process the elements that are added while looping through the list? 如何确保在遍历列表时处理添加的元素?

Main Thread: 主线程:

List<Object> someList = Collections.synchronizedList(new ArrayList<Object>());
for(Object o : someList){
    o.toString();
}

Some other Thread: 其他一些线程:

getSomeList().add(new Object());

Note: I want to process the object after i start looping through the list (or after that). 注意:我想在开始遍历列表之后(或之后)处理对象。

The only way to be able to add elements in thread A while thread B is looping through the list is for thread B make a copy of the list as it is at that exact point in time, then getting an Iterator or Enumerator from it. 在线程B遍历列表时,能够在线程A中添加元素的唯一方法是使线程B在该确切时间点复制列表,然后从中获取IteratorEnumerator If you don't make a copy before looping, then you'll get a ConcurrentModificationException if another thread adds an element while the other thread is looping. 如果在循环之前不进行复制,那么如果另一个线程在循环时添加了一个元素,则将获得ConcurrentModificationException

Using a synchronized java.util.List won't work since the iterator becomes invalid as soon as the source list is modified. 使用同步的java.util.List将不起作用,因为一旦修改了源列表,迭代器就会变得无效。 Sounds like you have a producer-consumer problem. 听起来您有生产者-消费者问题。 You should look into a Queue. 您应该查看一个队列。 Try java.util.Concurrent.LinkedBlockingQueue if you want an unbounded queue or java.util.concurrent.ArrayBlockingQueue if you want a blocking queue. 如果想要无限制的队列,请尝试java.util.Concurrent.LinkedBlockingQueue;如果想要阻塞的队列,请尝试java.util.concurrent.ArrayBlockingQueue。

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

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