您可能只需要实现自己的
BlockingQueue包装,即可将要约/投票映射到堆栈。然后将此作为
BlockingQueue您传递给的实现
ThreadPoolExecutor。我的建议是包装一个现有的
Deque实现,例如
ArrayDeque。
- 这是不同步的,因此您需要
BlockingQueue
使用同步器包装每个方法(如果不是更奇特的东西)。 - 您还需要为阻止操作引入
wait
/notify
条件。 - 最后,您需要将一组
BlockingQueue
极性(“放”侧或“取”侧)映射到出队的另一端(将其视为堆栈)。
请注意,在更快的并发堆栈上有一些工作(请参阅Herlihy的书, 《多处理器编程的艺术》
),但是我不认为JDK中有任何实现,而且我不确定Herlihy的实现是否提供了阻塞特性。
双端队列之上的实现
我查看了Android文档,这表明Deque在您身边,因此这里是一个实现。同样,在堆栈周围进行包装也很容易,但是Deque是首选。
import java.util.Collection;import java.util.Iterator;import java.util.NoSuchElementException;import java.util.concurrent.BlockingDeque;import java.util.concurrent.BlockingQueue;import java.util.concurrent.linkedBlockingDeque;import java.util.concurrent.TimeUnit;public final class BlockingLifoQueue<T> implements BlockingQueue<T>{ // we add and remove only from the end of the queue private final BlockingDeque<T> deque; public BlockingLifoQueue() { deque = new linkedBlockingDeque<T>(); } public boolean add(T e) { deque.addLast(e); return true; } public boolean contains(Object o) { return deque.contains(o); } public int drainTo(Collection<? super T> c) { return deque.drainTo(c); } public int drainTo(Collection<? super T> c, int maxElements) { return deque.drainTo(c,maxElements); } public boolean offer(T e) { return deque.offerLast(e); } public boolean offer(T e, long timeout, TimeUnit unit) throws InterruptedException { return deque.offerLast(e,timeout,unit); } public T poll(long timeout, TimeUnit unit) throws InterruptedException { return deque.pollLast(timeout, unit); } public void put(T e) throws InterruptedException { deque.putLast(e); } public int remainingCapacity() { return deque.size(); } public boolean remove(Object o) { return deque.remove(o); } public T take() throws InterruptedException { return deque.takeLast(); } public T element() { if (deque.isEmpty()) { throw new NoSuchElementException("empty stack"); } return deque.pollLast(); } public T peek() { return deque.peekLast(); } public T poll() { return deque.pollLast(); } // deque.peekLast(); } -- fixed typo. public T remove() { if (deque.isEmpty()) { throw new NoSuchElementException("empty stack"); } return deque.pollLast(); } public boolean addAll(Collection<? extends T> c) { for (T e : c) { deque.add(e); } return true; } public void clear() { deque.clear();} public boolean containsAll(Collection<?> c) { return deque.containsAll(c); } public boolean isEmpty() { return deque.isEmpty(); } public Iterator<T> iterator() { return deque.descendingIterator(); } public boolean removeAll(Collection<?> c) { return deque.removeAll(c); } public boolean retainAll(Collection<?> c) { return deque.retainAll(c); } public int size() { return deque.size(); } public Object[] toArray() { return deque.toArray(); } public <T> T[] toArray(T[] a) { return deque.toArray(a); }}


