手写阻塞队列
写个阻塞队列~~~
/**
* 手写阻塞队列
* ELEGANT
*/
public class MyBlockingQueue {
// 存储元素
private final Object[] items;
private int maxSize;
private int takeIndex = 0;
private int putIndex = 0;
private volatile int size = 0;
private ReentrantLock lock = new ReentrantLock();
private Condition takeCondition = lock.newCondition();
private Condition putCondition = lock.newCondition();
public MyBlockingQueue(int maxSize) throws Exception {
if (maxSize < 0){
throw new Exception("大小不能小于0");
}
this.maxSize = maxSize;
items = new Object[maxSize];
}
public Object take(){
lock.lock();
Object resp = null;
try {
while (size == 0){
System.out.println("没有东西拿");
takeCondition.await();
}
resp = items[takeIndex];
items[takeIndex] = null;
takeIndex = (takeIndex + 1) % items.length;
size--;
putCondition.signalAll();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
return resp;
}
public void put(Object x){
lock.lock();
try {
while (size == maxSize){
System.out.println("空间已满");
putCondition.await();
}
items[putIndex] = x;
putIndex = (putIndex + 1) % items.length;
size++;
takeCondition.signalAll();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws Exception {
MyBlockingQueue myBlockingQueue = new MyBlockingQueue(10);
new Thread(() -> {
while (true){
myBlockingQueue.put(10);
}
}).start();
new Thread(() -> {
while (true){
System.out.println(myBlockingQueue.take());
}
}).start();
}
}

浙公网安备 33010602011771号