生产消费的经典案例

package wan;

class wano {
    public static void main(String[] args) throws java.lang.Exception {

        Share sh = new Share();
        new Thread(new Producer(sh)).start();//同时启动两个线程
        new Thread(new Consumer(sh)).start();
    }
}

class Share {

    char ch;   //设定ch为全局变量,在整个类中可以用,用于存放生产了的数据给消费调用。
    boolean flag = false; 

    public synchronized void set() {
        char[] cha = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };

        for (char chari : cha) {  //等待和唤醒必须写在for循环里面

            if (flag) {

                try {
                    wait(); //等待消费取数
                } catch (InterruptedException e) {
                }

            }

            this.ch = chari;
            flag = true;
            notify();  //唤醒消费程序
        }

    }

    public synchronized void get() {
        if (!flag) {
            try {
                wait();  //等待生成
            } catch (InterruptedException e) {
            }

        }
        System.out.println("ch = " + this.ch);
        flag = false;
        notify();  //唤醒生产程序
    }
}

class Producer implements Runnable {
    Share sh = null;

    public Producer(Share sh) {
        this.sh = sh;
    }

    public void run() {

        this.sh.set();
    }
}

class Consumer implements Runnable {
    Share sh = null;

    public Consumer(Share sh) {
        this.sh = sh;
    }

    public void run() {
        for (int i = 0; i < 4; i++)
            this.sh.get();
    }
}
原文地址:https://www.cnblogs.com/dengnapianhuahai/p/5776388.html