gpt4 book ai didi

java - Java中是否有任何(无限制的)公平阻塞队列?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:27:16 26 4
gpt4 key购买 nike

如果多个消费者从同一个队列中删除元素,是否有任何阻塞队列的实现可以保证公平的 take() 操作。我检查了 LinkedBlockingQueue、LinkedTransferQueue,看起来它们都是不公平的。 ArrayBlockingQueue 提供了公平的操作,但它是有界的。

最佳答案

我们可以使用无界队列(如 ConcurrentLinked 队列)和公平信号量来实现无界公平阻塞队列。下面的类并没有实现 BlockingQueue 接口(interface)中的所有方法,只是实现了其中的一些用于演示目的。 main() 方法仅作为测试编写。

public class FairBlockingQueue<T> {

private final Queue<T> queue;
private final Semaphore takeSemaphore;

public FairBlockingQueue() {
queue = new ConcurrentLinkedQueue<T>();
takeSemaphore = new Semaphore(0, true);
}

public FairBlockingQueue(Collection<T> c) {
queue = new ConcurrentLinkedQueue<T>(c);
takeSemaphore = new Semaphore(c.size(), true);
}

public T poll() {
if (!takeSemaphore.tryAcquire()) {
return null;
}
return queue.poll();
}

public T poll(long millis) throws InterruptedException {
if (!takeSemaphore.tryAcquire(millis, TimeUnit.MILLISECONDS)) {
return null;
}
return queue.poll();
}

public T take() throws InterruptedException {
takeSemaphore.acquire();
return queue.poll();
}

public void add(T t) {
queue.add(t);
takeSemaphore.release();
}

public static void main(String[] args) throws Exception {
FairBlockingQueue<Object> q = new FairBlockingQueue<Object>();
Object o = q.poll();
assert o == null;
o = q.poll(1000);
assert o == null;

q.add(new Object());
q.add(new Object());
q.add(new Object());

o = q.take();
assert o != null;
o = q.poll();
assert o != null;
o = q.poll(1000);
assert o != null;

o = q.poll();
assert o == null;
}
}

关于java - Java中是否有任何(无限制的)公平阻塞队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4046838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com