1、生产者与消费者模式
多线程中,生成者与消费者是一个很典型的例子。生产者就是生产数据的线程,消费者就是消费数据的线程。生产者与消费者模式是通过一个共享资源缓冲区来解决生产者和消费者的强耦合问题,生产者与消费者之间不需要通信,生产者生产的产品放入阻塞队列中,而消费者从阻塞队列中从取出产品,阻塞队列就相当于一个缓冲区,
同时生成与消费还需要有一个生产与消费的平衡,这样讲生成者与消费者进行解耦。
2、代码实现
下面用生产汽车的简单例子说明:
/**
* 生成的汽车产品
*
*/
public class Car {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "汽车编号为:"+id;
}
}
/**
* 仓库对象,生产者生产的产品放在仓库中,供消费者从仓库中取产品
*
*/
public class DepotStack {
private final int MAXSIZE = 10;
BlockingQueue<Car> queues = new LinkedBlockingQueue<Car>(10);
//存产品
public void push(Car c){
// System.out.println("--------"+Thread.currentThread().getName()+"抢到资源");
if(queues.size()<MAXSIZE){
try {
queues.put(c);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"向仓库放入车"+c.getId());
}else{
System.out.println("仓库已存储满");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//取产品
public Car pop(){
Car c = null;
// System.out.println("*********"+Thread.currentThread().getName()+"抢到资源");
if(queues.size()==0){
try {
System.out.println("仓库为空");
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
c = queues.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"从仓库取出车"+c.getId());
return c;
}
}
public class Producer extends Thread{
private DepotStack depotStack;
public Producer(DepotStack depotStack) {
this.depotStack = depotStack;
}
@Override
public void run() {
while(true){
for (int i=0;i<10;i++) {
Car car = new Car();
car.setId(i);
depotStack.push(car);
}
}
}
}
/**
* 消费者
*
*/
public class Customer extends Thread{
private DepotStack depotStack;
public Customer(DepotStack depotStack) {
super();
this.depotStack = depotStack;
}
@Override
public void run() {
while (true) {
depotStack.pop();
}
}
}
public static void main(String[] args) {
DepotStack depotStack = new DepotStack();
Producer producer = new Producer(depotStack);
producer.setName("生成者1");
Customer customer = new Customer(depotStack);
customer.setName("消费者1");
producer.start();
customer.start();
}
测试结果: