手写一个简单的阻塞式队列
昨天齐老师的一个学生向他请教如何手写一个阻塞式队列,今天就教我们上手了。 这个是要求
- 不能使用jdk现有的任何Queue实现类
- 可以使用数组
- 满足先进先出
- 有界
下面是我自己写的,其实也不算是,思想是参考了算法书上的,老师写的比这好
class BQueueContainer<T> { private T[] arr; //数组 private int size; //容量 private int header; //头指针 private int tail; //尾指针 { header = tail = 0; // 初始化头尾指针 } // 为了方便测试,默认容量小了点 public BQueueContainer() { arr = (T[]) new Object[3]; size = 3; } //指定容量 public BQueueContainer(int capacity) { arr = (T[]) new Object[capacity]; size = capacity; } public synchronized void put(T t) { // 如果容器满了就阻塞 while ((tail + 1) % size == header) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //put one arr[tail++] = t; // tail++ if (tail >= size) { tail = 0; } //notify all this.notifyAll(); } public synchronized T get() { // if empty while ((header == 0 && tail == 0) || (header + 1) % size == tail) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // get one T t = arr[header++]; // header ++ if (header >= size) { header = 0; } //thread notify this.notifyAll(); return t; } @Override public String toString() { return Arrays.toString(arr); } }
下图为《数据结构与算法之美》 中关于这个的说明
下一篇:
常见算法-二叉树的后序遍历序列