生产者消费者

使用ReentrantLock和Condition解决

@Slf4j
public class Factory {

    ReentrantLock reentrantLock = new ReentrantLock();
    Condition conditionProducer = reentrantLock.newCondition();
    Condition conditionConsumer = reentrantLock.newCondition();

    Integer qty = 0;
    Integer max = 100;

    public void producer() {
        for (; ; ) {
            reentrantLock.lock();
            try {
                if (qty.equals(max)) {
                    conditionProducer.await();
                } else {
                    qty ++;
                    conditionConsumer.signalAll();
                    System.out.println("生产者 ----> 生产1,当前余量=" + qty);
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }
    }

    public void consumer() {
        for (; ; ) {
            reentrantLock.lock();
            try {
                if (qty.equals(0)) {
                    conditionConsumer.await();
                } else {
                    qty --;
                    conditionProducer.signalAll();
                    System.out.println("消费者 ----> 消费1,当前余量=" + qty);
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Factory factory = new Factory();
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                factory.producer();
                try {
                    Thread.sleep(200);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                factory.consumer();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();

        Thread.sleep(100000000);
    }