java消费者生产者设计模式_设计模式之生产者消费者模式

这个模式大部分都是用MQ(message queue 消息队列)在实际生产过程中实现的

要实现这个设计模式,就需要

原料:多个生产者线程生产商品(类比为list的add),多个消费者消费商品(类比为list的remove),商品的库存(一个同步的共享变量,list)

package design_pattern;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicInteger;

/**

* 生产者消费者模式 多线程生产消费 实现一个 笔试题

*/

public class ProducterAndConsumer {

public static void main(String[] args) throws InterruptedException {

//此处的商品不用list 而用juc包中的 线形阻塞队列来实现

BlockingQueue queue = new LinkedBlockingQueue(10);

ProducerThread p1 = new ProducerThread(queue);

ProducerThread p2 = new ProducerThread(queue);

ConsumerThread c = new ConsumerThread(queue);

p1.start();

p2.start();

c.start();

// 执行10秒

Thread.sleep(10 * 1000);

p1.stopThread();

p2.stopThread();

}

}

class ProducerThread extends Thread {

private BlockingQueue queue;

private boolean flag = true;

// 原子类变量,此处用juc的原子类来记录 生产和消费的编号

public static AtomicInteger count = new AtomicInteger();

public ProducerThread(BlockingQueue queue) {

this.queue = queue;

}

@Override

public void run() {

// TODO Auto-generated method stub

try {

System.out.println("生产线程启动");

while (flag) {

System.out.println("正在生产者队列");

String data = count.incrementAndGet() + "";

// 添加队列

boolean offer = queue.offer(data);

String msg = null;

if (offer) {

msg = Thread.currentThread().getName()+"生产者生产" + data + "成功";

} else {

msg = "生产者生产" + data + "失败";

}

System.out.println(msg);

Thread.sleep(1000);

}

} catch (Exception e) {

} finally {

System.out.println("生产者线程停止");

}

}

public void stopThread() {

flag = false;

}

}

class ConsumerThread extends Thread {

private BlockingQueue queue;

private boolean flag = true;

public ConsumerThread(BlockingQueue queue) {

this.queue = queue;

}

@Override

public void run() {

System.out.println("消费者线程进行消费");

try {

while (flag) {

// 获取完毕,队列删除掉用poll方法获取

String data = (String) queue.poll(2, TimeUnit.SECONDS);

if (null != data) {

System.out.println("消费者消费" + data + "成功");

} else {

System.out.println("消费者消费" + data + "失败");

this.flag=false;

}

}

} catch (Exception e) {

} finally {

System.out.println("消费停止");

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值