繁体   English   中英

另一个线程从队列中删除了元素?

[英]Another thread removed element from queue?

我有多个使用共享变量queue线程。 处理(打印)后,它将从队列中删除该元素

protected void tryToPrint() {
    while (true) {
        try {
            if (printer.isAvailable() && printer.isFair(this)) {
                queueLock.lock();
                try {
                    if (queue.isEmpty()) 
                        break;

                    printer.requestToPrint(this, queue.get(0));
                    queue.remove(0);
                    synchronized (System.out) {
                        System.out.println(getName() + " printed. queue size: " + queue.size());
                    }
                } finally {
                    queueLock.unlock();
                }
            } else {
                printer.requestToPrintNext(this);
            }
        } catch (IllegalPrintStateException e) {
            e.printStackTrace();
        }
    }
}

但是我越来越

Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.remove(ArrayList.java:445)
    at printer.ClientImpl.tryToPrint(ClientImpl.java:34)
    at printer.AbstractClient.run(AbstractClient.java:28)
    at java.lang.Thread.run(Thread.java:722)

我想另一个线程以某种方式从队列中删除了一个元素? 我怎么可能将其锁定?

更新 :队列实际上是一个ArrayList<File>() 它不是线程安全的是否重要? 我锁定了queueLock吗?

关于您的特定示例,queueLock是什么? 它在哪里创建? 它是否在线程之间共享(例如,静态-我的猜测是不,这可能会导致您的问题)? 需要更多信息。

如果您不想担心所有这些问题,则只需使用同步将其重写。 更简单...

protected void tryToPrint() {
    while (true) {
        try {
            if (printer.isAvailable() && printer.isFair(this)) {
                synchronized(queue) {
                    if (queue.isEmpty()) 
                        break;

                    printer.requestToPrint(this, queue.get(0));
                    queue.remove(0);
                    synchronized (System.out) {
                        System.out.println(getName() + " printed. queue size: " + queue.size());
                    }
                }
            } else {
                printer.requestToPrintNext(this);
            }
        } catch (IllegalPrintStateException e) {
            e.printStackTrace();
        }
    }
}

暂无
暂无

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

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