Java实现阻塞队列
程序员文章站
2024-03-18 11:17:40
...
Java实现阻塞队列
1、生产者向队尾添加元素;
2、消费者向队头消费元素;
3、添加和消费过程是线程安全的;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class MyBlockingQueueLock<T> {
private Queue<T> queue = new LinkedList<>();
private final int MAX;
private ReentrantLock lock = new ReentrantLock();
private Condition producer = lock.newCondition();
private Condition consumer = lock.newCondition();
public MyBlockingQueueLock(int limit){
this.MAX=limit;
}
public void put(T t) throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (queue.size() == MAX){
producer.await();
}
queue.offer(t);
}finally {
lock.unlock();
}
}
public T get() throws InterruptedException {
final ReentrantLock lock=this.lock;
T t;
lock.lockInterruptibly();
try {
while (queue.size()==0){
consumer.await();
}
t=queue.poll();
producer.signalAll();
}finally {
lock.unlock();
}
return t;
}
}
上一篇: 数组队列