生产者和消费者模型

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];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值