笔试题:单消费者和单生产者的问题

来源:互联网 发布:农村淘宝是做什么的? 编辑:程序博客网 时间:2024/05/17 03:17

题目:实现一个单消费者和单生产者的问题,中间容器使用栈。

/* * 生产者 */public class Producer implements Runnable {    private int id;//为多生产者和多消费者留    SynContainer ct = null;    public Producer(int id, SynContainer ct) {        this.id = id;        this.ct = ct;    }    public void run() {        for(int i=0; i<20; i++) {            Baozi bz = new Baozi(i);            ct.push(bz);            int j = bz.getId() + 1;System.out.println("生产者生产的第" + j + "包子");        }    }}

/* * 消费者 */public class Consumer implements Runnable {    private int id;//为多生产者和多消费者留    SynContainer ct = null;    Consumer(int id, SynContainer ct) {        this.id = id;        this.ct = ct;    }    public void run() {        for(int i=0; i<20; i++) {            Baozi bz = ct.pop();            int j = bz.getId() + 1;System.out.println("----------------------这是消费者吃掉的第" + j + "个包子");            try {                Thread.sleep(2000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

/** 栈容器*/public class SynContainer {    int index = 0;//栈容器的指针    Baozi[] array = new Baozi[6];    /*     * 往容器里面放包子     */    public synchronized void push(Baozi bz) {        if(index == array.length) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.notify();        array[index] = bz;        index++;    }    /*     * 从容器里面向外面取包子     */    public synchronized Baozi pop() {        if(index == 0) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.notify();        index--;        Baozi bz = array[index];        array[index] = null;         return bz;    }}

/* * 生产的产品:包子 */public class Baozi {    private int id;    Baozi(int id) {        this.setId(id);    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }}

/** 测试程序 */public class Test {    public static void main(String[] args) {        SynContainer ct = new SynContainer();        Producer p = new Producer(1, ct);        Consumer c = new Consumer(1, ct);        new Thread(p).start();        new Thread(c).start();    }}
3 0
原创粉丝点击