同步 LinkedList 中的 java.util.NoSuchElementException

标签 java multithreading concurrency linked-list synchronization

以下同步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/

相关文章:

java - 使用 FileInputStream 读取 xml 文件

java - 将字符串转换为 w3c.dom.Element : XMLParseException:Start of root element expected

java - 如何在java中对Hashtable进行洗牌

c++ - 在 gtest 中运行线程

c# - List<T> 并发删除和添加

java - 在 Guava 中链接 Future 时处理异常

java - Java 中的 System.exit(0)

java - java 中的多线程 - 4 个线程自动执行相同的操作

solaris - 多线程 printf 与 write(2) 缓冲

python - 使用 call_soon() 和 ensure_future() 的区别