以下同步Queue
被多个生产者和消费者访问,它是同步的,但在从队列中提取元素时仍然给出java.util.NoSuchElementException
。这是什么问题以及如何解决。
public class Que{
private Queue queue = new LinkedList();
public synchronized void enqueue(Runnable r) {
queue.add(r);
notifyAll();
}
public synchronized Object dequeue(){
Object object = null;
try{
while(queue.isEmpty()){
wait();
}
} catch (InterruptedException ie) {
}
object = (Object)queue.remove();// This line is generating exception
return object;
}
}
最佳答案
我发现了这个问题,并且已经解决了。 发生了InterruptedException,需要在catch语句中恢复中断状态并返回,如下。
public class Que{
private Queue queue = new LinkedList();
public synchronized void enqueue(Runnable e) {
queue.add(e);
notifyAll();
}
public synchronized Object dequeue(){
Object object = null;
try{
while(queue.isEmpty()){
wait();
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();//restore the status
return ie;//return InterruptedException object
}
object = (Object)queue.remove();// This line is generating exception
return object;
}
}
关于同步 LinkedList 中的 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118126/