gpt4 book ai didi

同步 LinkedList 中的 java.util.NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 13:40:41 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com