Java ReEntrantLock 之 Condition条件(Java代码实战-002)

Posted FrankYou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java ReEntrantLock 之 Condition条件(Java代码实战-002)相关的知识,希望对你有一定的参考价值。

 

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ConditionTest
 * 一个测试类,用Condition实现的生产者消费者问题
 */
public class ConditionTest {
    /* 定义一个容器(链表、队列) */
    private LinkedList<String> buffer;
    /* 容器可以容纳元素的最大数量,通过构造函数来初始化 */
    private int maxSize;
    private Lock lock;
    private Condition fullCondition;
    private Condition notFullCondition;

    ConditionTest(int maxSize) {
        this.maxSize = maxSize;
        buffer = new LinkedList<String>();
        lock = new ReentrantLock();
        fullCondition = lock.newCondition();
        notFullCondition = lock.newCondition();
    }

    /**
     * 向容器中放入Element
     */
    public void set(String string) throws InterruptedException {
        // 获取锁
        lock.lock();
        try {
            while (maxSize == buffer.size()) {
                // 满了,添加的线程进入等待状态
                notFullCondition.await();
            }
            buffer.add(string);

            // 容器不为空时,则给等待的读取的线程发送信号以便唤醒这些线程进行读取
            fullCondition.signal();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 从容器中获取Element
     */
    public String get() throws InterruptedException {
        String string;
        lock.lock();
        try {
            while (buffer.size() == 0) {
                // 如果容器为空,则读取的线程进入等待状态
                fullCondition.await();
            }
            string = buffer.poll();

            // 给写入的线程发送信号以便唤醒这些线程来往容器中写入
            notFullCondition.signal();
        } finally {
            lock.unlock();
        }
        return string;
    }
}

 

以上是关于Java ReEntrantLock 之 Condition条件(Java代码实战-002)的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程之ReentrantLock与Condition

java 多线程之ReentrantLock与condition

JAVA并发之ReentrantLock源码

Java多线程系列--“JUC锁”02之 互斥锁ReentrantLock

Java多线程之ReentrantLock与Condition

Java ReEntrantLock 之 Condition条件(Java代码实战-002)