[英]Implementing a synchronized queue in Java using ArrayList
我一直在做一个需要同步队列的项目,因为我的程序是多线程的,线程可以访问这个队列。 我使用arraylist来做到这一点,但我似乎有一些问题,线程陷入僵局。 我不知道队列是否是原因,但我只想检查:
public class URLQueue {
private ArrayList<URL> urls;
public URLQueue() {
urls = new ArrayList<URL>();
}
public synchronized URL remove() throws InterruptedException {
while (urls.isEmpty())
wait();
URL r = urls.remove(0);
notifyAll();
return r;
}
public synchronized void add(URL newURL) throws InterruptedException {
urls.add(newURL);
notifyAll();
}
public int getSize() {
return urls.size();
}
}
编辑:即使使用LinkedBlockingQueue,我也会遇到与以前相同的循环。 我认为这是因为有一个线程正在等待队列被填充,但它永远不会,因为其他功能已经完成运行...任何想法???
最好在这里使用LinkedBlockingQueue
,因为它是为此目的而设计的。 它会等到某个元素可用时才会尝试删除。
它提供了一个take()
方法
检索并删除此队列的头部,必要时等待,直到元素可用
在您的代码中, notifyAll()
不会抛出InterruptedException,因此您应该从add()
删除throws
remove()
方法不需要notifyAll()
因为它的动作不应该唤醒其他线程。
应该同步getSize()
方法。
否则,您的代码没有机会死锁,因为您需要两个锁来创建死锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.