zoukankan      html  css  js  c++  java
  • 使用Lock实现信号量

    public class SemaphoreOnLock
    {
        private final Lock lock = new ReentrantLock();
       
        private final Condition permitsAvailable = lock.newCondition();
       
        private int permits;
       
        SemaphoreOnLock(int initialPermits)
        {
            lock.lock();
           
            try
            {
                permits = initialPermits;
            }
            finally
            {
                lock.unlock();
            }
        }
       
        public void acquire()
            throws InterruptedException
        {
            lock.lock();
           
            try
            {
                while (permits <= 0)
                {
                    permitsAvailable.await();
                }
               
                --permits;
            }
            finally
            {
                lock.unlock();
            }
        }
       
        public void release()
        {
            lock.lock();
           
            try
            {
                ++permits;
                permitsAvailable.signal();
            }
            finally
            {
                lock.unlock();
            }
           
        }
    }

  • 相关阅读:
    对函数的推广
    自然语言也支持泛型
    用委托实现对List的常用方法提取
    C#中的特性(Attributes)(翻译)(转)
    用JQUERY增删元素
    表格折叠展开
    下一代编程语言可能具有的特点
    一种多继承方案
    几年前毕业设计做的CAD二次开发
    数据结构 003.1.1 栈的基本概念
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3293936.html
Copyright © 2011-2022 走看看