代码语言:javascript复制
class MyBlockingQueue {
private String[] elems = null;
private int head = 0;
private int tail = 0;
private int size = 0;
private Object locker = new Object();//锁对象
public MyBlockingQueue(int capacity) {
elems = new String[capacity];
}
public void put(String elem) throws InterruptedException {
synchronized (locker) {
while (size >= elems.length) {
//队列满了,产生阻塞
locker.wait();
}
elems[tail] = elem;
tail ;
if (tail >= elems.length) { //循环队列
tail = 0;
}
size ;
locker.notify(); //入队之后重新唤醒
}
}
public String take() throws InterruptedException {
String elem = null;
synchronized (locker) {
while (size == 0) {
locker.wait();//队列空了,产生阻塞
}
elem = elems[head];
head ;
if (head >= elems.length) {
head = 0;
}
size --;
locker.notify();//元素出队列之后, 唤醒
}
return elem;
}
}
1.通过"循环队列" 的方式来实现 2. 使用 synchronized 进行加锁控制. 3.put 插⼊元素的时候, 判定如果队列满了, 就进⾏ wait. (注意, 要在循环中进⾏ wait 被唤醒时不⼀定 队列就不满了,因为同时可能是唤醒了多个线程). 4. take 取出元素的时候, 判定如果队列为空, 就进⾏ wait. (也是循环 wait).