多线程 生产,消费 ProducerConsumerDemo

ProducerConsumerDemo.java

/**
 * 资源类
 */
class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() {
        lock.lock(); //加锁

        //1. 判断
        while (number != 0) {
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 干活
        number++;
        System.out.println(Thread.currentThread().getName() + " " + number);

        // 通知唤醒
        condition.signalAll();

        lock.unlock(); // 释放锁
    }

    public void decrement() {
        lock.lock(); //加锁

        //1. 判断
        while (number == 0) {
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 干活
        number--;
        System.out.println(Thread.currentThread().getName() + " " + number);

        // 通知唤醒
        condition.signalAll();

        lock.unlock(); // 释放锁
    }

}

/**
 * 1 线程 操作,资源类
 * 2 判断 干活 通知
 * 3 防止虚假唤醒机制
 */
public class ProducerConsumerDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.increment();
            }
        },"aa").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.decrement();
            }
        },"bb").start();
    }
}

结果:

aa 1 bb 0 aa 1 bb 0 aa 1 bb 0 aa 1 bb 0 aa 1 bb 0
经验分享 程序员 微信小程序 职场和发展