在同步的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;
}
}