简体   繁体   English

如何使用线程将对象添加到列表并同时使用该列表而不会获得 ConcurrentModificationException?

[英]How to add objects to a list with a thread and use the list at the same time without getting ConcurrentModificationException?

The title tells it all, I have a Timer t1 which periodically adds objects to a List.标题说明了一切,我有一个 Timer t1,它定期将对象添加到列表中。 Then I have an other Timer t2 iterating on the list at constant intervals to display its content.然后我有另一个 Timer t2 以恒定间隔在列表上迭代以显示其内容。

I totaly understand why i'm getting these exceptions but I can't come up with the right answer to avoid it.我完全理解为什么我会收到这些异常,但我无法想出正确的答案来避免它。 Iv'e tried running my operations in synchronized(list){} and such things but nothing makes it.我试过在 synchronized(list){} 和类似的东西中运行我的操作,但没有成功。 My algorithm apears to be working just fine despite these exceptions but i would like to make it clean nontheless.尽管有这些例外,我的算法似乎工作得很好,但我还是想让它干净。

Any idea?任何的想法?

Edit: I'm using java.util.Timer;编辑:我正在使用 java.util.Timer;

All access to the List much be wrapped by a synchronized block like so:对 List 的所有访问都被一个同步块包裹,如下所示:

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public final class Answer {
    private static final int FIVE_SECONDS = 5 * 1000;
    private static final int TWO_SECONDS = 2 * 1000;

    public static void main(String... args) {
        // this list contains the values that the producer will add to and the consumer will pull from
        final List<Long> theList = new ArrayList<>();

        // consumes all values found in theList
        new Timer("consumer").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                final List<Long> copy;
                synchronized (theList) {
                    // we make a copy and clear theArray as quickly as possible in 
                    // order to not block the producer for too long
                    copy = new ArrayList<>(theList);
                    theList.clear();
                }

                System.out.println("copy = " + copy);
            }
        }, 1, FIVE_SECONDS);

        // adds the current time in ms to theList every 2 seconds
        new Timer("producer").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                synchronized (theList) {
                    theList.add(System.currentTimeMillis());
                }
            }
        }, 1, TWO_SECONDS);
    }
}

That being said using a BlockingQueue will do this for you.话虽如此,使用 BlockingQueue 将为您做到这一点。

https://www.baeldung.com/java-mutex也许看看 mutex-structures,这些可能会派上用场

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

相关问题 从 ArrayList 同时删除两个对象而不导致 ConcurrentModificationException? - Remove two objects at the same time from an ArrayList without causing a ConcurrentModificationException? 如何在没有ConcurrentModificationException的情况下删除List迭代 - How to remove List iteration without ConcurrentModificationException 修改获取ConcurrentModificationException的列表映射 - modify a list map getting ConcurrentModificationException 列出ConcurrentModificationException - List ConcurrentModificationException Java在没有ConcurrentModificationException的情况下在同一循环中添加/删除 - Java add/remove at the same loop without ConcurrentModificationException 处理List上的并发修改而没有ConcurrentModificationException - Deal with concurrent modification on List without having ConcurrentModificationException 如何在Java的同一列表中添加多个对象类型 - How to add multiple objects types in the same list in Java 为什么我在同时迭代和修改HashMap时没有得到“ConcurrentModificationException”? - How come I am not getting “ConcurrentModificationException” while iterating and modifying on HashMap at the same time? Java ConcurrentModificationException 用于从多线程写入数组列表 - Java ConcurrentModificationException for writing to array list from multiple thread 如何将列表中的对象添加到向量? - How to add objects in a List to a Vector?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM