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

  • 相关阅读:
    Android(java)学习笔记15:匿名内部类实现多线程
    Android(java)学习笔记14:Java线程池
    Android(java)学习笔记13:线程组的概述和使用
    Android(java)学习笔记12:线程的状态转换图以及常见执行情况
    win2012R2打Windows8.1-KB2919355 问题
    win2012R2打Windows8.1-KB2919355 问题
    P2404
    P2404
    P2404
    抽签
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3293936.html
Copyright © 2011-2022 走看看