生产者,消费者模式
简介:把需要生产的产品单独当做一个类,用户需要商品的时候,是直接在工厂(容器)中取拿,而不会关心你的生产过程。也就是说,生产者把东西生产好之后,放入到一个容器里。消费者去容器里去拿,而不是去联系生产者,实现了功能的分离
需要被生产的产品类
public class Computer {
private String brand;
private int id;
public Computer(int id) {
this.id = id;
}
public Computer(String brand, int id) {
this.brand = brand;
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Computer{" +
"brand='" + brand + '\'' +
", id=" + id +
'}';
}
}
存放产品的工厂
public class CompuerContainer {
//工厂容量
Computer[] computers = new Computer[5];
private int index = 0;
//创建锁,防止多个线程同时把造好的电脑放入仓库,使仓库容量大于5,这个锁是属于工厂里面的,跟外部没有什么关系
private Lock lock = new ReentrantLock();
//创建存放休眠的生产者、消费者队列,便于唤醒,提高效率
Condition pro_condition = lock.newCondition();
Condition con_condition = lock.newCondition();
public void make(Computer computer) {
lock.lock();
try {
//如果存货满了,则不能再生产,生产线程等待
while (index > 4) {
try {
pro_condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (computer.getId() % 2 == 0) {
computer.setBrand("外星人");
} else {
computer.setBrand("联想");
}
computers[index] = computer;
System.out.println(computer.getBrand() + " " + computer.getId() + "号被生产了");
index++;
//唤醒消费队列
con_condition.signal();
} finally {
lock.unlock();
}
}
public void bring(){
lock.lock();
while (index < 1) {
try {
con_condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
Computer computer = computers[index];
computers[index] = null;
System.out.println(computer.getId() + computer.getBrand() + "被买走了,老板大气");
//唤醒生产者队列
pro_condition.signal();
}
}
生产者类,需要传入一个工厂,保证生产者、消费者都是对一个工厂进行的操作
public class Producer implements Runnable {
CompuerContainer compuerContainer;
public Producer(CompuerContainer compuerContainer) {
this.compuerContainer = compuerContainer;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
compuerContainer.make(new Computer(i));
}
}
}
消费者类
public class Consumer implements Runnable{
CompuerContainer compuerContainer;
public Consumer(CompuerContainer compuerContainer) {
this.compuerContainer = compuerContainer;
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
compuerContainer.bring();
}
}
}
测试类
public class Demo {
public static void main(String[] args) {
CompuerContainer compuerContainer = new CompuerContainer();
Producer producer = new Producer(compuerContainer);
Consumer consumer = new Consumer(compuerContainer);
new Thread(producer, "工人").start();
new Thread(consumer, "马老板").start();
}
}
执行结果