[TOC]

Semaphore

简介

  1. Semaphore是一个计数信号量,采用的是共享锁的方式控制

方法

  1. acquire(int)来获取信号量,直到只有一个可以用或者出现中断。
  2. release(int)用来释放信号量,将信号量数量返回给Semaphore

源码分析

构造函数

  1. 构造函数

            public Semaphore(int permits) {
             sync = new NonfairSync(permits);
         }
    
         /***
         *初始化Semaphore时需要指定共享资源的个数。Semaphore提供了两种模式:公平模式&非公平模式。
         *如果不指定工作模式的话,默认工作在非公平模式下
         **/
         public Semaphore(int permits, boolean fair) {
             sync = fair ? new FairSync(permits) : new NonfairSync(permits);
         }
    

获取资源

  1. Semaphore提供两种获取资源的方式:响应中断和不响应中断

       public void acquire() throws InterruptedException {
             sync.acquireSharedInterruptibly(1);
         }
       public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
             //先检测中断,然后调用tryAcquireShared视图获取共享资源   
             if (Thread.interrupted())
                 throw new InterruptedException();
             if (tryAcquireShared(arg) < 0)
                 doAcquireSharedInterruptibly(arg);
         }
    

results matching ""

    No results matching ""