wait notify,实现生产与消费的和谐

之前的代码没有考虑容器里为空的现象,当生产一个商品时,可能cpu会在消费者里一直运行,从而消费多个空产品。wait是一个异常,使用时要进行捕获。notify是苏醒线程。

class Resourse {
    private Object[] os = new Object[1];
    private Object obj = new Object();

    public void put(Object o) {
        synchronized (obj) {
            if (os[0] != null) {//给一个判断,如果容器里还有商品那么就让线程等一下
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                }
            }
            os[0] = o;
            System.out.println(Thread.currentThread().getName() + "生产出来的---" + os[0]);
            obj.notify();//既然有等待那么就要有苏醒。
        }
    }

    public void get() {
        synchronized (obj) {
            if (os [0]== null) {//给一个判断,如果容器里没有商品那么就让线程等一下
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName() + "消耗的---" + os[0]);
            os[0] = null;
            obj.notify();
        }
    }
}

class Sheng implements Runnable {
    private Resourse r;

    Sheng(Resourse r) {
        this.r = r;
    }

    public void run() {
        int num = 0;
        while (true) {

            r.put("自行车" + num);
            num++;

        }
    }
}

class Xiao implements Runnable {
    private Resourse r;

    Xiao(Resourse r) {
        this.r = r;
    }

    public void run() {
        while (true) {
            int num = 0;
            r.get();
            num++;

        }
    }
}

class Demo1 {
    public static void main(String[] args) {
        Resourse r = new Resourse();
        Sheng s = new Sheng(r);
        Xiao x = new Xiao(r);
        Thread ss = new Thread(s);
        Thread ss2 = new Thread(x);
        ss.start();
        ss2.start();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容