侧边栏壁纸
博主头像
昊天的个人博客 博主等级

行动起来,活在当下

  • 累计撰写 65 篇文章
  • 累计创建 72 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

ReentranLock 实现生产者消费者

昊天
2022-03-29 / 0 评论 / 0 点赞 / 42 阅读 / 0 字
    static ReentrantLock lock = new ReentrantLock();
    static Condition empty = lock.newCondition();
    static Condition full = lock.newCondition();
    static volatile int size = 0;
    static final int max_size = 10;

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Consumer().start();
            new Producer().start();
        }
    }

    static class Consumer  extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            lock.lock();
            while (size == 0) {
                empty.await();
            }
            System.out.println("消费"+size);
            size--;
            full.signal();
            lock.unlock();
        }
    }

    static class Producer  extends Thread {
        @SneakyThrows
        @Override
        public void run() {
            lock.lock();
            while (size == max_size) {
                full.await();
            }
            size++;
            System.out.println("生产"+size);
            empty.signal();
            lock.unlock();

        }
    }
0

评论区