生产者消费者模式

来源:互联网 发布:阿里云tv输入法apk 编辑:程序博客网 时间:2024/06/06 02:44

注:一个生产者,一个消费者。

1.测试类

/** * 生产者消费者模式 * 有两个角色,生产者和消费者 * 生产者负责生产,消费者负责消费 * 生产者生产的商品,交给消费者来消费,商品数据在生产者和消费者之间共享 * 商品数量不能为负数,商品需要有地方来保存(比如仓库),所以商品数量还应该有上限(商品数量最多不能超过某个数) * 当商品数量为0时,消费者不能继续消费 * 当商品数量达到上限时,生产者不能继续生产 */public class Test {    public static void main(String[] args) {        Factory f = new Factory();        Runnable worker = new Worker(f);        Runnable customer = new Customer(f);        new Thread(worker,"a").start();        new Thread(customer,"b").start();    }}

2.Facroty(仓库)

/** * 仓库,用来保存商品 */public class Factory {    private Integer num = 10;//商品数量    /**     * 生产的方法     */    public synchronized void enterProduct(){        //如果商品数量大于等于10个,就不允许再生产了        if(num>=10){            System.out.println("商品数量过多,不能再生产了");            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        try {            Thread.sleep(300);        } catch (InterruptedException e) {            e.printStackTrace();        }        num++;        System.out.println("生产了一个商品,现在的商品数量:"+num);        this.notify();        //this.notifyAll();    }    /**     * 消费的方法     */    public synchronized void outProduct(){        //当商品数量为0时,消费者不能继续消费        if(num<=0){            System.out.println("没有商品了,现在不能消费了");            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        try {            Thread.sleep(300);        } catch (InterruptedException e) {            e.printStackTrace();        }        num--;        System.out.println("消费了一个商品,现在的商品数量:"+num);        this.notify();    }}

3.生产者:

public class Worker implements Runnable {    private Factory factory;    public Worker(Factory factory){        this.factory = factory;    }    @Override    public void run() {        while(true){            //不断生产            factory.enterProduct();        }    }}

4.消费者:

public class Customer implements Runnable {    private Factory factory;    public Customer(Factory factory) {        this.factory = factory;    }    @Override    public void run() {        while(true){            factory.outProduct();        }    }}

这里写图片描述

0 0
原创粉丝点击