有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用ArrayList在Java中实现同步队列

我的多线程访问队列可能是因为我的项目需要同步的原因。 我使用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时,我也会像以前一样陷入相同的循环中。我认为这是因为有一个线程正在等待队列被填充,但它从来没有这样做,因为其他功能都在运行。。。有什么想法吗


共 (2) 个答案

  1. # 1 楼答案

    在代码中,notifyAll()不会引发InterruptedException,因此应该从add()中删除throws

    remove()方法不需要notifyAll(),因为它的操作不应该唤醒其他线程

    getSize()方法应该同步

    否则,代码就不会死锁,因为需要两个锁来创建死锁

  2. # 2 楼答案

    最好在这里使用LinkedBlockingQueue,因为它是为此而设计的。在尝试删除某个元素时,它会等待某个元素可用

    LinkedBlockingQueue

    它提供了一个take()方法

    Retrieves and removes the head of this queue, waiting if necessary until an element becomes available