[英]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.