java实现生产者消费者模型

生产者消费者问题是多线程的一个经典问题,它描述是有一块缓冲区作为仓库,生产者可以将产品放入仓库,消费者则可以从仓库中取走产品。
主要思路是利用BlockingQueue队列模拟实现仓库
put()方法:类似于我们上面的生产者线程,容量达到最大时,自动阻塞。
take()方法:类似于我们上面的消费者线程,容量为0时,自动阻塞。
生产者。

public class Producer implements Runnable {
    BlockingQueue<String> queue; 

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }
    public void run() {
        // TODO 自动生成的方法存根
        try{
            String temp = "A prodcut.生产线程:" 
                    + Thread.currentThread().getName();
            System.out.println("I have made a Product:"
                    + Thread.currentThread().getName());
            queue.put(temp);//如果队列满的话,会阻塞当前线程
        }catch(InterruptedException e) {
            e.printStackTrace();
        }

    }

}

消费者

public class Consumer implements Runnable {
    BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        try{
            String temp = queue.take(); //如果队列为空,会阻塞当前线程
            System.out.println(temp);
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }

}

测试程序

public class Test {
    public static void main(String[] args) {
        BlockingQueue<String> queue = new LinkedBlockingQueue<String>(2);//设置缓冲区大小
        Consumer consumer = new Consumer(queue);
        Producer producer = new Producer(queue);
        for(int i = 0; i < 5; i++) {
            new Thread(producer,"Producer" + (i + 1)).start();
            new Thread(consumer,"Consumer" + (i + 1)).start();
        }
    }
}

结果:

I have made a Product:Producer1
I have made a Product:Producer4
I have made a Product:Producer3
I have made a Product:Producer2
A prodcut.生产线程:Producer1
A prodcut.生产线程:Producer4
I have made a Product:Producer5
A prodcut.生产线程:Producer3
A prodcut.生产线程:Producer2
A prodcut.生产线程:Producer5
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值