zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    how to uninstall devkit
    asp.net中bin目录下的 dll.refresh文件
    查找2个分支的共同父节点
    Three ways to do WCF instance management
    WCF Concurrency (Single, Multiple, and Reentrant) and Throttling
    检查string是否为double
    How to hide TabPage from TabControl
    获取当前系统中的时区
    git svn cygwin_exception
    lodoop打印控制具体解释
  • 原文地址:https://www.cnblogs.com/frankyou/p/9054879.html
Copyright © 2011-2022 走看看