Object.wait()实现生产者消费者模式

主调用程序:

public class MainDemo {
    public static void main(String[] args) {
        Box box=new Box();

        Product product=new Product(box);
        Customer customer =new Customer(box);

        Thread th1=new Thread(product);
        Thread th2=new Thread(customer);

        th1.start();
        th2.start();

    }
}

共享资源类:

/*
* 共享数据区
* */
public class Box {
    private int milk;
    private boolean state=false;

    /*
    * 加锁调用
    * */
    public synchronized void put(int milk)
    {
        if (state){
            try {
                /* 事件锁:
                * 1.不带参数:导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法。
                * 2.带参数重载:导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法,或指定的时间已过。
                * */
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.milk=milk;

        System.out.println("放入:"+this.milk);

        this.state=true;

        /*
        * 唤醒正在等待对象监视器的所有线程。
        * */
        notifyAll();
    }

    public synchronized void get(){
        if (!state){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("取出:"+milk);

        state=false;

        notifyAll();
    }
}

生产者:

/*
* 生产者类
* */
public class Product implements Runnable {
    private Box box;

    public Product(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        for (int i=1;i<11;i++){
            box.put(i);
        }
    }
}

消费者:

/*
* 消费者类
* */
public class Customer implements Runnable {
    private Box box;

    public Customer(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            box.get();
        }
    }
}
原文地址:https://www.cnblogs.com/zhuyapeng/p/13825777.html