阻塞队列实现生产者消费者

阻塞队列:BlockingQueue

当队列是空的,从队列中获取元素(take()方法)的操作将会被阻塞
当队列是满的,从队列中添加元素(put()方法)的操作将会被阻塞

这里使用无界队列LinkBlockingQueue实现(默认大小为integer.MAX_VALUE)

具体实现代码:


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 使用无界阻塞队列linkblockingQueue实现生产者消费者
 */
class ProductPool {

    private BlockingQueue producstPool = new LinkedBlockingQueue();

    public ProductPool(BlockingQueue producstPool) {
        this.producstPool = producstPool;
    }

    /**
     * 生成产品
     */
    public void product(Integer product) throws InterruptedException {
        producstPool.put( product);
        System.out.println(Thread.currentThread().getName()+"生成了"+product+"号产品");
    }

    /**
     * 消费产品
     * @throws InterruptedException
     */
    public void consumr() throws InterruptedException {
        Integer take = (Integer) producstPool.take();
        System.out.println(Thread.currentThread().getName()+"消费了"+take+"号产品");
    }
}


/**
 * @author 79282
 */
public class LinkBlockKingQueue {


    public static void main(String[] args) {
        ProductPool productPool = new ProductPool(new LinkedBlockingQueue());
        new Thread(()->{
            for (int i = 1; i <= 50; i++) {
                try {
                    productPool.product(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"生产者线程").start();


        new Thread(()->{
            for (int i = 1; i <= 50; i++) {
                try {
                    productPool.consumr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"消费者线程").start();
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值