生产者消费者问题

来源:互联网 发布:mac本地音乐播放器 编辑:程序博客网 时间:2024/06/04 12:28

消费者生产者问题描述:有一个容器,其中生产者负责向容器中装入苹果,消费者负责从容器中取出苹果,规则要求是容器中最多能装下6个苹果,但容器中有6个苹果时,生产者再也不能向容器中加入苹果,只有当容器中的苹果数量少于6个时,才能再次添加。但容器中的苹果数量为零时,消费者不能从容器中取出,只有当容器中的苹果数量大于0时才能取出。java代码实现如下:

package com.gdut.wang;public class Apple {    private int id;    public Apple(int id) {        super();        this.id = id;    }    @Override    public String toString() {        return "Apple [id=" + id + "]";    }}

package com.gdut.wang;public class AppleStack {    private Apple[] arrApple = new Apple[6];    private int index;    public synchronized Apple pop() {        if (index == 0)            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        this.notify();        index--;        return arrApple[index];    }    public synchronized void push(Apple apple) {        if (index == arrApple.length)            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        this.notify();        arrApple[index] = apple;        index++;    }}

package com.gdut.wang;public class Productor implements Runnable {    private AppleStack as;    public Productor(AppleStack as) {        super();        this.as = as;    }    @Override    public void run() {        for (int i = 0; i < 20; i++) {            Apple apple = new Apple(i);            as.push(apple);            System.out.println("放入第" + i + "个苹果");            try {                Thread.sleep((int) (Math.random() * 1000));            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

package com.gdut.wang;public class Consumer implements Runnable {    private AppleStack as;    public Consumer(AppleStack as) {        super();        this.as = as;    }    @Override    public void run() {        for (int i = 0; i < 20; i++) {            Apple apple = as.pop();            System.out.println("拿出了第" + i + "苹果");            try {                Thread.sleep((int) (Math.random() * 1000));            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

package com.gdut.wang;public class ProductorConsumer {    private static AppleStack as = new AppleStack();    private static Consumer c = new Consumer(as);    private static Productor p = new Productor(as);    public static void main(String[] args) {        new Thread(p).start();        new Thread(c).start();    }}
0 0
原创粉丝点击