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;
    }
}

 

posted @ 2018-05-18 10:19  FrankYou  阅读(327)  评论(0编辑  收藏  举报