欢迎光临散文网 会员登陆 & 注册

线程的生产者和消费者管程法的代码

2020-04-15 10:27 作者:小垃圾kiki  | 我要投稿
package cn.jd.cooperation;

/*
 * 使用管程法实现生产者消费者模式
 */
public class CoTest01 {
    public static void main(String[] args) {
        SynContainer container=new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}

//多线程的生产者
class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        // 生产
        for (int i = 1; i < 100; i++) {
            System.out.println("生产第 -->"+i+"个馒头");
            container.push(new Steamedbun(i)); //new了馒头的对象
        }
    }
}

//多线程的消费者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        // 消费
        for (int i = 0; i < 1000; i++) {
            System.out.println("消费第-->"+container.pop().id+"个馒头");
            
        }
    }
}

//缓冲区
class SynContainer {
    // 存储数据的容器
    Steamedbun[] buns = new Steamedbun[10];
    int count = 0;// 计数器
    // 储存-->生产者做的事情

    public synchronized void push(Steamedbun bun) {
        //何时能生产  容器存在空间
        //不能生产  只有等待
        if(count==buns.length) {
            try {
                this.wait();    //线程阻塞,消费者通知生产解除
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }
        }
        //存在空间可以生产
        buns[count] = bun;
        count++;
        //存在数据了,可以通知消费了
        this.notifyAll();
    }

    // 获取-->消费者做的事情
    public synchronized Steamedbun pop() {
        //何时消费    看容器中是否存在数据
        //没有数据只有等待
        if(count==0) {
            try {
                this.wait();//线程阻塞   生产者通知消费解除阻塞
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //存在数据可以消费
        count--;
        Steamedbun bun = buns[count];
        this.notifyAll();//消费了有空间了就可以通知你生产了
        return bun;
    }

}

//馒头
class Steamedbun {
        int id;

        public Steamedbun(int id) {
            this.id = id;
        }
        
}

线程的生产者和消费者管程法的代码的评论 (共 条)

分享到微博请遵守国家法律