假设我有 BlockingQueue 并且一些线程被称为 take() 但此时队列是空的。并且假设我以某种方式知道将来新元素不会出现在队列中。如何从等待中释放那些被称为 take() 的线程?谢谢!
public void run() {
//noinspection InfiniteLoopStatement
while (true) {
try {
Thread.sleep(millisecondsToSleep);
if (!kitchen.processedOrdersEmpty()) {
Order processedOrder = kitchen.getFromProcessedOrders();
kitchen.printMessage("took order#" + processedOrder.getOrderNumber());
Thread.sleep(millisecondsToServe);
kitchen.printMessage("served order#" + processedOrder.getOrderNumber());
} else {
int currentRandom = getNextRandom();
if (currentRandom <= 10) {
Order newOrder = new Order(kitchen.getLastOrderNumber());
kitchen.puIntoUnprocessedOrders(newOrder);
kitchen.printMessage("generated new order#" + newOrder.getOrderNumber());
} else {
Thread.sleep(millisecondsToSleep);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
其中 kitchen.getFromProcessedOrders() 等于:
public Order getFromProcessedOrders() throws InterruptedException {
return processedOrders.take();
}
和 processesOrders 是一个 BlockingQueue