1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| /** * @author : sungm * @date : 2020-09-04 16:31 */ public class BlockingQueue<T> {
private LinkedList<T> queue = new LinkedList<>(); private int limit = 16;
/** * 构造方法注入阻塞队列的上线 * * @param limit 阻塞队列的限制 */ public BlockingQueue(int limit) { this.limit = limit; }
/** * 入队操作 * * @param node 入队元素 * @return boolean 结果 * @throws InterruptedException e */ public synchronized boolean enqueue(T node) throws InterruptedException { while (queue.size() == limit) { wait(); } notifyAll(); return queue.add(node); }
/** * 出队操作 * * @return T 出队元素 * @throws InterruptedException e */ public synchronized T dequeue() throws InterruptedException { while (queue.size() == 0) { wait(); } notifyAll(); //第一个元素出队并删除引用 return queue.removeFirst(); }
}
|