給定一個BlockingQueue<E>
實例的集合,在整個集合上實現阻塞take()
和poll()
的最有效方式是什麼?下面是代碼:阻塞隊列的「聯合」的實現
class UnionBlockingQueue<E> implements BlockingQueue<E> {
private final Collection<BlockingQueue<E>> sources;
public UnionBlockingQueue(Collection<BlockingQueue<E>> sources) {
this.sources = sources;
}
@Override
public E take() throws InterruptedException {
// takes first available E from the sources
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
// polls first available E from the sources
}
// The rest is unsupported/irrelevant/out of scope
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
@Override
public boolean offer(E e) {
throw new UnsupportedOperationException();
}
}
我正打算包裝在一個單獨的類中的每個源隊列這將重寫add /報價方法和觸發這個類的notFull
和notEmpty
條件,就像在Condition樣品使用,但是,對於Java隊列是新手,我認爲可能會有更好/更安全/更高效的方法或庫。
如果你有能力包裝源隊列並重寫'add'和'offer',那麼你不能簡單地向所有生產者發出一個隊列嗎? – teppic
@teppic因爲它不一樣,每個人都可以重寫,但並不是每個人都有能力改變應用程序的設計,所有我在這裏給出的是一組隊列。 – Osw
也許我誤解了你的意思是「覆蓋」。您是否控制生產者用戶的隊列實例的類型或實例化? – teppic