Java可阻塞队列的两种实现方式

在Java中,对于Lock和Condition可以理解为对传统的synchronized和wait/notify机制的替代。

wait/notify有个限制,调用wait/notify的线程必须持有对象的锁。

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException - if the current thread is not the owner of this object's monitor.

通常使用wait/notify的代码是这个样子的:

synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }

在Condition接口的javadoc中,有一个经典的Condition例子,用Condition实现了一个可阻塞队列。这里仿照javadoc简单实现了一个可阻塞队列。为了简单,没有进行try/catch,同时加入了一些注释。


public class BoundedBuffer {
    final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();

final Object[] items = new Object[2]; // 阻塞队列
int putptr, takeptr, count;

public void put(Object x) throws InterruptedException {
    System.out.println("进入put");
    lock.lock();
    System.out.println("put lock 锁住");
    try {
        while (count == items.length) { // 如果队列满了,notFull就一直等待
            System.out.println("put notFull 等待");
            notFull.await(); // 调用await的意思取反,及not notFull -> Full
        }
        items[putptr] = x; // 终于可以插入队列
        if (++putptr == items.length)
            putptr = 0; // 如果下标到达数组边界,循环下标置为0
        ++count;
        System.out.println("put notEmpty 唤醒");
        notEmpty.signal(); // 唤醒notEmpty
    } finally {
        System.out.println("put lock 解锁");
        lock.unlock();
    }
}

public Object take() throws InterruptedException {
    lock.lock();
    System.out.println("take lock 锁住");
    try {
        while (count == 0) {
            System.out.println("take notEmpty 等待");
            notEmpty.await();
        }
        Object x = items[takeptr];
        if (++takeptr == items.length)
            takeptr = 0;
        --count;
        System.out.println("take notFull 唤醒");
        notFull.signal();
        return x;
    } finally {
        lock.unlock();
        System.out.println("take lock 解锁");
    }
}

public static void main(String[] args) throws InterruptedException {
    final BoundedBuffer bb = new BoundedBuffer();
    System.out.println(Thread.currentThread()+","+bb);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread()+","+bb);
                bb.put("xx");
                bb.put("yy");
                bb.put("zz");
                                    bb.put("zz");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
    bb.take();
}
}

如果不使用JUC,大概是这样的:


public class BoundedBuffer_Synchronized {
private Object[] items = new Object[2];
private Object notEmpty = new Object();
private Object notFull = new Object();
int count,putidx,takeidx;

public  void put(Object obj) throws InterruptedException{
    synchronized(notFull){
        while(count == items.length){
            notFull.wait();
        }
    }
    items[putidx] = obj;
    if(++putidx == items.length){
        putidx = 0;
    }
    count ++;
    synchronized (notEmpty) {
        notEmpty.notify();
    }
}
public Object take() throws InterruptedException{
    synchronized(notEmpty){
        while(count == 0){ // 啥也没有呢 取啥
            notEmpty.wait();
        }
    }
    Object x = items[takeidx];
    System.out.println("取第"+takeidx+"个元素"+x);
    if(++takeidx == items.length){
        takeidx = 0; 
    }
    count --;
    synchronized (notFull) {
        notFull.notify();
    }
    return x;
}
public static void main(String[] args) throws InterruptedException {
    final BoundedBuffer_Synchronized bb = new BoundedBuffer_Synchronized();
    System.out.println(Thread.currentThread()+","+bb);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread()+","+bb);
                bb.put("xx");
                bb.put("yy");
                bb.put("zz");
                bb.put("zz");
                bb.put("zz");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
    bb.take();
    bb.take();
}
}

从功能上来讲,两者实现了可阻塞队列的基本业务需求。Condition是配合Lock使用的,而wait/notify是配合synchronized使用的。比较两种实现方式,其实就是比较Lock和synchronized两种同步机制的区别。关于这方面,可以参考Java 理论与实践: JDK 5.0 中更灵活、更具可伸缩性的锁定机制

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java的Map是一种键值对的数据结构,它提供了快速的访问和查找功能。但是,Map并不是一个阻塞队列,它不能直接用来实现阻塞队列功能。但是,我们可以使用Map来实现一个阻塞队列,具体实现方法如下: 1. 创建一个Map对象,用来存储队列元素。 2. 创建一个互斥锁对象,用来保证队列操作的线程安全。 3. 创建两个条件变量,一个用来表示队列已满,另一个用来表示队列为空。 4. 实现队列的put方法,当队列已满时,阻塞当前线程,等待队列有空闲位置。 5. 实现队列的take方法,当队列为空时,阻塞当前线程,等待队列有元素可取。 6. 实现队列的size方法,返回队列元素的数量。 下面是一个使用Map实现阻塞队列的示例码: ``` import java.util.Map; import java.util.HashMap; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class BlockingQueue<T> { private final Map<Integer, T> map; private final Lock lock; private final Condition notFull; private final Condition notEmpty; private int capacity; private int head; private int tail; public BlockingQueue(int capacity) { this.capacity = capacity; map = new HashMap<>(capacity); lock = new ReentrantLock(); notFull = lock.newCondition(); notEmpty = lock.newCondition(); head = 0; tail = 0; } public void put(T element) throws InterruptedException { lock.lock(); try { while (tail - head == capacity) { notFull.await(); } map.put(tail % capacity, element); tail++; notEmpty.signal(); } finally { lock.unlock(); } } public T take() throws InterruptedException { lock.lock(); try { while (tail == head) { notEmpty.await(); } T element = map.remove(head % capacity); head++; notFull.signal(); return element; } finally { lock.unlock(); } } public int size() { lock.lock(); try { return tail - head; } finally { lock.unlock(); } } } ``` 在这个示例,我们使用了一个Map来存储队列元素,并使用了一个互斥锁和两个条件变量来实现阻塞队列的功能。put方法和take方法分别实现了向队列添加元素和从队列取出元素的功能。size方法返回队列元素的数量。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值