简体   繁体   English

同步LinkedList中的java.util.NoSuchElementException

[英]java.util.NoSuchElementException in synchronized LinkedList

Following synchronized Queue is accessed by number of producers and consumers, it is synchronized but it is still giving java.util.NoSuchElementException when extracting element from queue. 跟随同步Queue由生产者和消费者的数量访问,它是同步的,但是当从队列java.util.NoSuchElementException提取元素时它仍然给出java.util.NoSuchElementException What is the matter with it and how to resolve it. 它有什么问题以及如何解决它。

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;
    }

}

I found the problem and i have resolved it too. 我发现了问题,我也解决了。 InterruptedException has occured and the interrupted status need to be restored in the catch statement and also need to be return as follows. 发生了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;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM