码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-18 11:26:23      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:list   ant   线程   函数   ted   ==   容器   string   发送   

 

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)

标签:list   ant   线程   函数   ted   ==   容器   string   发送   

原文地址:https://www.cnblogs.com/frankyou/p/9054879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!