wait/notify 实现生产者消费者模式

发布时间 2023-09-12 17:13:05作者: jishaling
public class Test1 {

    private Logger logger = LoggerFactory.getLogger(Test1.class);
    private int max = 2;
    private LinkedList<Object> storage = new LinkedList<>();

    public synchronized void put() throws InterruptedException {
        while (storage.size() == max){
            wait();
        }
        storage.add(new Object());
        logger.info("put:", Thread.currentThread().getName());
        notifyAll();
    }

    public synchronized void get() throws InterruptedException {
        while (storage.size() == 0){
            wait();
        }
        storage.remove();
        logger.info("remove:", Thread.currentThread().getName());
        notifyAll();
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        Producer producer = new Producer(test1);
        Consumer consumer = new Consumer(test1);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

class Producer implements Runnable{
    private Test1 test1;

    public Producer(Test1 test1){
        this.test1 = test1;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                test1.put();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Consumer implements Runnable{
    private Test1 test1;

    public Consumer(Test1 test1){
        this.test1 = test1;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                test1.get();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}