多线程生产者和消费者

多线程生产者和消费者

public class TestDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

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

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.increment();
            }
        }).start();
    }
}

class ShareData {
    private int number = 0;
    private ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println("加操作。。。");
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println("减操作。。。");
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

posted @ 2022-09-29 17:31  紫川先生  阅读(11)  评论(0编辑  收藏  举报