实现多线程堆栈,可以自由使用现有堆栈 堆栈的实现。除了线程安全之外,它还必须阻止 (不是忙等待)堆栈已满且弹出时的推送线程 堆栈为空时使用线程。它必须发出信号使线程退出睡眠状态 当堆栈再次有空间或元素弹出时。在这个问题中,公平性是可选的。
如何在Java中实现这样的堆栈?我想出了以下实施方案。这是解决上述问题的正确方法吗?
public class MyStack<E> {
private final Stack<E> stack;
private int max = 16;
private final ReentrantLock lock = new ReentrantLock(true);
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
public MyStack(int size) {
this.stack = new Stack<>();
this.max = size;
}
public void push(E e) {
lock.lock();
try {
while (stack.size() == max) {
notFull.await();
}
stack.push(e);
notEmpty.signalAll();
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
lock.unlock();
}
}
public E pop() {
lock.lock();
try {
while (stack.size() == 0) {
notEmpty.await();
}
E item = stack.pop();
notFull.signalAll();
return item;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}