使用Lock锁及Condition实现自定义阻塞队列

前言

Lock锁相对于传统的synchronized关键字来说更加灵活,Lock锁为我们提供了显示加锁、可中断加锁、超时加锁等机制。

Lock锁 VS synchronized锁:

  • 二则都是可重入锁
  • synchronized是关键字,不会导致死锁,而Lock可能会出现死锁;
  • synchronized不能响应中断,获取不到锁会一直阻塞,而Lock可以响应中断,可以知道是否获取了锁
  • synchronized为独占锁,锁的获取和释放由JVM实现
实现阻塞队列

阻塞队列要点:

  1. 当队列中没有元素时就阻塞,有则返回元素;
  2. 当队列已满时阻塞,未满时将元素放入队列;

这里我们要结合使用JUC包下的Condition,对线程的阻塞与执行实现更加灵活的控制

实现如下:(建议在多线程下多测试几次,观察各个线程的加锁解锁过程)


public class CustomBlockingQueue {
    // 这里我们用ArrayList模拟队列
    private List<Object> queue = new ArrayList<>();

    // 创建lock对象,同时创建两个condition实例,分别用于控制阻塞队列的读和写
    private Lock lock = new ReentrantLock();
    private Condition putCondition = lock.newCondition();
    private Condition takeCondition = lock.newCondition();

    // 阻塞队列的大小
    private int size;

    public CustomBlockingQueue(int size) {
        this.size = size;
    }

    /**
     * 向阻塞队列放入元素,如果队列已满则阻塞
     *
     * @param obj 放入队列的元素
     */
    public void put(Object obj) {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + " got the lock ... " + lock);
        try {
            while (true) {
                // 如果队列未满,则放入元素
                if (queue.size() < size) {
                    queue.add(obj);
                    System.out.println(Thread.currentThread().getName() + " add to queue: " + obj);
                    takeCondition.signal();
                    break;
                } else {
                    // 队列已满,则阻塞
                    System.out.println(Thread.currentThread().getName() + " want to add a obj but queue is full...");
                    putCondition.await();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " release the lock ... " + lock);
            lock.unlock();
        }

    }

    /**
     * 从阻塞队列获取元素,如果队列为空则阻塞
     *
     * @return 获取的元素
     */
    public Object take() {
        lock.lock();
        System.out.println(Thread.currentThread().getName() + " got the lock ... " + lock);
        Object obj = null;
        try {
            while (true) {
            	// 如果队列不为空,则获取队头元素
                if (queue.size() > 0) {
                    obj = queue.remove(0);
                    System.out.println(Thread.currentThread().getName() + " get a obj: " + obj);
                    putCondition.signal();
                    return obj;
                } else {
                	// 队列为空,阻塞
                    System.out.println(Thread.currentThread().getName() + " want to get a obj but no one...");
                    takeCondition.await();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " release the lock ... " + lock);
            lock.unlock();
        }
        return obj;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你实现一个基于ReentrantLockCondition的简单阻塞队列。 首先,我们需要定义一个队列类,包含以下方法: - `enqueue(item)`:将元素放入队列中。 - `dequeue()`:从队列中取出元素。 - `size()`:返回队列的大小。 下面是使用ReentrantLockCondition实现的代码: ```java import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class BlockingQueue<T> { private Queue<T> queue; private int maxSize; private ReentrantLock lock; private Condition notEmpty; private Condition notFull; public BlockingQueue(int maxSize) { this.maxSize = maxSize; this.queue = new LinkedList<>(); this.lock = new ReentrantLock(); this.notEmpty = lock.newCondition(); this.notFull = lock.newCondition(); } public void enqueue(T item) throws InterruptedException { lock.lock(); try { while (queue.size() == maxSize) { // 队列已满,等待直到队列不满 notFull.await(); } queue.add(item); notEmpty.signalAll(); // 通知等待中的线程队列不为空 } finally { lock.unlock(); } } public T dequeue() throws InterruptedException { lock.lock(); try { while (queue.isEmpty()) { // 队列为空,等待直到队列不为空 notEmpty.await(); } T item = queue.remove(); notFull.signalAll(); // 通知等待中的线程队列不满 return item; } finally { lock.unlock(); } } public int size() { lock.lock(); try { return queue.size(); } finally { lock.unlock(); } } } ``` 使用这个阻塞队列的示例代码如下: ```java public class Main { public static void main(String[] args) { BlockingQueue<Integer> queue = new BlockingQueue<>(5); Thread producer = new Thread(() -> { for (int i = 0; i < 10; i++) { try { queue.enqueue(i); System.out.println("Produced: " + i); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread consumer = new Thread(() -> { for (int i = 0; i < 10; i++) { try { int item = queue.dequeue(); System.out.println("Consumed: " + item); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); producer.start(); consumer.start(); } } ``` 在这个示例中,生产者线程不断地将元素放入队列中,消费者线程不断地从队列中取出元素。当队列已满时,生产者线程会被阻塞,直到有空余位置;当队列为空时,消费者线程会被阻塞,直到有元素可取。 希望这个简单的阻塞队列实现对你有帮助!如果还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值