生产者和消费者模型

来源:互联网 发布:淘宝中年女秋装新款 编辑:程序博客网 时间:2024/04/25 23:57
public class ProductAndConsumer {    public static void main(String[] args) {        StackBasket s = new StackBasket();        Producer p = new Producer(s);        Consumer c = new Consumer(s);        Thread tp = new Thread(p);        Thread tc = new Thread(c);        tp.start();        tc.start();    }}//class Apple {    private int id;    Apple(int id) {        this.id = id;    }    public String toString() {        return "Apple: " + id;    }}class Producer implements Runnable {    StackBasket ss = new StackBasket();    Producer(StackBasket ss) {        this.ss = ss;    }    public void run() {        int i = 0;        for (;;) {            Apple m = new Apple(i++);            ss.push(m);            try {                Thread.sleep((int) (Math.random() * 500));            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}class Consumer implements Runnable {    StackBasket ss = new StackBasket();    Consumer(StackBasket ss) {        this.ss = ss;    }    public void run() {        for (;;) {            Apple m = ss.pop();            try {                Thread.sleep((int) (Math.random() * 1000));            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}class StackBasket {    Apple sm[] = new Apple[5];    int index = 0;    public synchronized void push(Apple m) {        try {            while (index == sm.length) {                System.out.println("!!!!!!!!!No place to apple!!!!!!!!!");                this.wait();            }            this.notify();        } catch (InterruptedException e) {            e.printStackTrace();        } catch (IllegalMonitorStateException e) {            e.printStackTrace();        }        sm[index] = m;        index++;        System.out.println("Product " + m + " total " + index + " apples");    }    public synchronized Apple pop() {        try {            while (index == 0) {                System.out.println("!!!!!!!!!No Apple!!!!!!!!!");                this.wait();            }            this.notify();        } catch (InterruptedException e) {            e.printStackTrace();        } catch (IllegalMonitorStateException e) {            e.printStackTrace();        }        index--;        System.out.println("Consum " + sm[index] + " total " + index                                   + " Apples");        return sm[index];    }}

0 0
原创粉丝点击