我们用循环队列的方法,然后在对应的方法上加上一定的限制方法构建出一个阻塞队列
package 阻塞队列;
public class Test2 {
static class BlockingQueue {
private int[] array = new int[100];
private volatile int head = 0;
private volatile int tail = 0;
private volatile int size = 0;
public void put(int v) throws InterruptedException {
synchronized (this) {
while (size == array.length) {
wait();
}
array[tail] = v;
tail++;
if (tail == array.length) {
tail = 0;
}
size++;
notify();
}
}
public int take() throws InterruptedException {
int ret = -1;
synchronized (this) {
while (size == 0) {
wait();
}
ret = array[head];
head++;
if (head == array.length) {
head = 0;
}
size--;
notify();
}
return ret;
}
}
}