menu 李昊天的个人博客
ReentranLock 实现生产者消费者
131 浏览 | 2022-03-29 | 分类:JAVA | 标签:多线程
    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();

        }
    }
知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

发表评论

email
web

全部评论 (暂无评论)

info 还没有任何评论,你来说两句呐!