同步LinkedList中的java.util.NoSuchElementException
以下同步的同步LinkedList中的java.util.NoSuchElementException,java,multithreading,concurrency,linked-list,synchronization,Java,Multithreading,Concurrency,Linked List,Synchronization,以下同步的队列由生产者和消费者的数量访问,它是同步的,但在从队列提取元素时仍然给出java.util.NoSuchElementException。问题是什么?如何解决 public class Que{ private Queue queue = new LinkedList(); public synchronized void enqueue(Runnable r) { queue.add(r); notifyAll(); }
队列
由生产者和消费者的数量访问,它是同步的,但在从队列提取元素时仍然给出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;
}
}
可能发生了中断异常?我认为它是
队列。添加(r)
应该是队列。添加(e)
?aguibert你是对的,这是我这里的一个打字错误,但它不是在我的真实代码中。返回异常似乎不太可能是正确的选择。我不会返回异常。你只应该扔它。