线程安全问题 [英] Thread safety issue
问题描述
我有一个包含对象的 LinkedList,我想处理它.对象从另一个线程添加到它,但只有一个线程从中删除/读取.
I have a LinkedList with Objects, that I want to process. Objects get added to it from another thread, but only one Thread removes/reads from it.
private LinkedList<MyObject> queue = new LinkedList<>();
new Thread()
{
@Override
public void run()
{
while (!Thread.interrupted())
{
if (!queue.isEmpty())
{
MyObject first = queue.removeFirst();
// do sth..
}
}
}
}.start();
在另一个线程中,我将对象添加到队列中
In another Thread I add Objects to the queue
queue.add(new MyObject());
虽然有时这段代码会导致异常,但我无法真正向自己解释.线程"中的异常 java.util.NoSuchElementException在 java.util.LinkedList.removeFirst(LinkedList.java:270)
Sometimes this code leads to an Exception though, which I cant really explain to myself. Exception in thread "" java.util.NoSuchElementException at java.util.LinkedList.removeFirst(LinkedList.java:270)
我不明白,为什么我会收到此异常,因为它应该只尝试删除存在的对象.
I dont get, why I get this Exception, since it should only try to remove an object if one exists.
推荐答案
正如 Nicolas 已经提到的,您需要一个线程安全的实现.我建议使用 LinkedBlockingQueue
.
As Nicolas has already mentioned, you need a thread safe implementation. I would recommend using LinkedBlockingQueue
.
您可以使用 offer
方法添加并使用 take
删除,这也将解决您的忙等待"问题.
You can add to it using offer
method and remove using take
which will also resolve your "busy waiting" problem.
这篇关于线程安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!