java 简单阻塞队列,java condition 实现简单的阻塞队列

上一篇文章介绍了condition的使用方法

这一篇文章介绍如何用condition来实现一个简单的阻塞队列 消费者 生产者模式。

消费者 生产者模式就是 生产者生产某些对象,消费者来消费这些对象。其中用对象数组来保存这些对象,既然是数组,在初始化的时候需要指定数组的大小。

在生产者生产的时候需要检查数组是否已经满了,如果满了,那么生产者会被挂起,等到有消费者消费对象时,再进行生产。

当消费者消费的时候,先检查数组是否为空,如果为空会被挂起,等到生产者生产出对象时,再被唤醒,进行消费,这样就简单实现了一个简单的阻塞队列。

下面 上代码。

MyQueue

335b83df261c422459d4afc29ba290e5.png

d1b641f023dd079c9e4a800b96607d9d.gif

packagecom.citi.test.mutiplethread.demo5;importjava.util.Arrays;importjava.util.concurrent.locks.Condition;importjava.util.concurrent.locks.ReentrantLock;public class MyQueue{publicObject[] obj;private intaddIndex;private intremoveIndex;private intqueueSize;private ReentrantLock lock=newReentrantLock();private Condition addCondition=lock.newCondition();private Condition removeCondition=lock.newCondition();public MyQueue(intcount) {

obj=newObject[count];

}publicObject get(){return obj[queueSize-1];

}public voidadd(E e){

lock.lock();while(queueSize==obj.length){

System.out.println(Thread.currentThread().getName()+" 队列已满,不进行添加、");try{

addCondition.await();

}catch(InterruptedException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}

}

obj[addIndex]=e;if(++addIndex==obj.length){

addIndex=0;

}

queueSize++;

removeCondition.signal();

System.out.println(Thread.currentThread().getName()+"生产之后:"+Arrays.toString(obj));

lock.unlock();

}public voidremove(){

lock.lock();while(queueSize==0){

System.out.println(Thread.currentThread().getName()+" 队列为空,不进行移除、");try{

removeCondition.await();

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

obj[removeIndex]=null;if(++removeIndex==obj.length){

removeIndex=0;

}

queueSize--;

addCondition.signal();

System.out.println(Thread.currentThread().getName()+"消费之后:"+Arrays.toString(obj));

lock.unlock();

}

}

View Code

MyQueueAdd 生产者

335b83df261c422459d4afc29ba290e5.png

d1b641f023dd079c9e4a800b96607d9d.gif

packagecom.citi.test.mutiplethread.demo5;importjava.util.UUID;public class MyQueueAdd implementsRunnable {private MyQueuequeue;public MyQueueAdd(MyQueuequeue) {this.queue=queue;

}

@Overridepublic voidrun() {while(true){

queue.add(UUID.randomUUID().toString());try{

Thread.sleep(1000);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}//System.out.println(Thread.currentThread().getName()+":生产者添加元素"+Arrays.toString(queue.obj));

}

}

}

View Code

MyQueueRemove 消费者

335b83df261c422459d4afc29ba290e5.png

d1b641f023dd079c9e4a800b96607d9d.gif

packagecom.citi.test.mutiplethread.demo5;public class MyQueueRemove implementsRunnable {private MyQueuequeue;public MyQueueRemove(MyQueuequeue) {this.queue =queue;

}

@Overridepublic voidrun() {while(true){

queue.remove();try{

Thread.sleep(1000);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}//System.out.println(Thread.currentThread().getName()+":消费者删除:"+Arrays.toString(queue.obj));

}

}

}

View Code

TestMyQueue 测试类 生产者大于消费者

335b83df261c422459d4afc29ba290e5.png

d1b641f023dd079c9e4a800b96607d9d.gif

packagecom.citi.test.mutiplethread.demo5;public classTestMyQueue {public static voidmain(String[] args) {

MyQueue queue=new MyQueue(10);

MyQueueAdd add=newMyQueueAdd(queue);

MyQueueRemove remove=newMyQueueRemove(queue);newThread(add).start();newThread(add).start();newThread(add).start();newThread(add).start();newThread(remove).start();

}

}

View Code

下面是执行结果,可以看到当队列为空时,消费者会被挂起,直到有生产者生产出对象,唤醒消费者,消费者再进行消费。因为生产者的个数大于消费者的个数,所以等到数组满了之后,出现队列已满,不进行添加。

20190921211626648736.png

下面将消费者的个数大于生产者的个数

代码

335b83df261c422459d4afc29ba290e5.png

d1b641f023dd079c9e4a800b96607d9d.gif

packagecom.citi.test.mutiplethread.demo5;public classTestMyQueue {public static voidmain(String[] args) {

MyQueue queue=new MyQueue(10);

MyQueueAdd add=newMyQueueAdd(queue);

MyQueueRemove remove=newMyQueueRemove(queue);newThread(add).start();newThread(remove).start();newThread(remove).start();newThread(remove).start();newThread(remove).start();

}

}

View Code

下面是执行结果。

20190921211626760068.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你实现一个基于ReentrantLock和Condition简单阻塞队列。 首先,我们需要定义一个队列类,包含以下方法: - `enqueue(item)`:将元素放入队列中。 - `dequeue()`:从队列中取出元素。 - `size()`:返回队列的大小。 下面是使用ReentrantLock和Condition实现的代码: ```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、付费专栏及课程。

余额充值