java并发工具类-Semaphore信号量

概念

Semaphore翻译成字面意思为 信号量,Semaphore可以控同时访问的线程个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

  Semaphore类位于java.util.concurrent包下,它提供了2个构造器:

public Semaphore(int permits) {          //参数permits表示许可数目,即同时可以允许多少线程进行访问
    sync = new NonfairSync(permits);
}

public Semaphore(int permits, boolean fair) {    //这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
    sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
}

  下面说一下Semaphore类中比较重要的几个方法,首先是acquire()、release()方法:

public void acquire() throws InterruptedException {  }     //获取一个许可
public void acquire(int permits) throws InterruptedException { }    //获取permits个许可
public void release() { }          //释放一个许可
public void release(int permits) { }    //释放permits个许可

  acquire()用来获取一个许可,若无许可能够获得,则会一直等待,直到获得许可。

  release()用来释放许可。注意,在释放许可之前,必须先获获得许可。

  这4个方法都会被阻塞,如果想立即得到执行结果,可以使用下面几个方法:

public boolean tryAcquire() { };    //尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { };  //尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
public boolean tryAcquire(int permits) { }; //尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false

  另外还可以通过availablePermits()方法得到可用的许可数目。

使用场景

对资源的锁定,比如连接池最大连接的个数

使用案例

  下面通过一个例子来看一下Semaphore的具体使用:

  假若一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,其他工人才能继续使用。那么我们就可以通过Semaphore来实现:

public class Test {

public static void main(String[] args) {
    int N = 8;            //工人数
    Semaphore semaphore = new Semaphore(5); //机器数目
    for(int i=0;i<N;i++)
        new Worker(i,semaphore).start();
}
 
static class Worker extends Thread{
    private int num;
    private Semaphore semaphore;
    public Worker(int num,Semaphore semaphore){
        this.num = num;
        this.semaphore = semaphore;
    }
     
    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println("工人"+this.num+"占用一个机器在生产...");
            Thread.sleep(2000);
            System.out.println("工人"+this.num+"释放出机器");
            semaphore.release();           
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}
  执行结果:

工人0占用一个机器在生产...
工人1占用一个机器在生产...
工人2占用一个机器在生产...
工人4占用一个机器在生产...
工人5占用一个机器在生产...
工人0释放出机器
工人2释放出机器
工人3占用一个机器在生产...
工人7占用一个机器在生产...
工人4释放出机器
工人5释放出机器
工人1释放出机器
工人6占用一个机器在生产...
工人3释放出机器
工人7释放出机器
工人6释放出机器

已有 17 条评论
  1. StevWews

    Generic Propecia Review Comprar Cialis En Tenerife cialis generic Propecia Alicante Colchicine From Canada Acheter Du Viagra En Andorre

    StevWews December 3rd, 2019 at 10:15 am回复
  2. LesAstona

    Viagra Alternative Apotheke Cialis Uso cialis price Purchasing Bentyl Discount Medicine Mastercard Levitra Costo Farmacia

    LesAstona January 18th, 2020 at 03:02 pm回复
  3. MatInfoge

    Global Pharmacy Canada http://buyciallisonline.com - Buy Cialis Levitra Originale Prezzo In Farmacia Cialis Propecia Side Effect

    MatInfoge January 28th, 2020 at 10:55 am回复
  4. LesAstona

    How Can I Get Some Acyclovir http://cheapcialisir.com - buy cialis Jelly Kamagra Paypal Cialis Viagra Sale Pfizer

    LesAstona February 3rd, 2020 at 04:30 pm回复
  5. StevWews

    Antibiotic Amoxicillin Dosage http://buyciallisonline.com/# - Cialis Cialis 20 Mg Generico Cialis Dove Acquistare Cialis Sicuro

    StevWews February 8th, 2020 at 09:17 pm回复
  6. LesAstona

    Zithromax And Doxycycline http://abcialisnews.com - cialis online Amoxacillin From Canada Cialis Prednisone Brand For Sale

    LesAstona February 22nd, 2020 at 01:17 pm回复
  7. EllEarnef

    Online Drug Stores In Canada https://buyciallisonline.com/# - cialis Direct Bentyl 20mg Buying Internet On Line buy generic cialis online Cialis Crea Adiccion

    EllEarnef March 2nd, 2020 at 03:01 am回复
  8. Stepsok

    Vendite Kamagra Cialis Keflex Is Used For canadian pharmacy cialis 20mg Kamagra Pas Cher 150 Mg

    Stepsok March 8th, 2020 at 11:30 am回复
  9. Stepsok

    Where To Buy Viagra Over The Counter buy cialis online Priligy Generika Dapoxetine Kaufen viagra vs cialis Propecia Hsa Eligible

    Stepsok March 8th, 2020 at 08:38 pm回复
  10. Janmit

    Comprare Viagra Online Italia cialis Propecia Produttore Cialis Levaquin Want To Buy

    Janmit March 13th, 2020 at 02:45 pm回复
  11. Stepsok

    Vente Viagra Ligne France En Lille Buy Cialis Viagra 50 Mg Prezzo Farmacia cialis Productos Con Kamagra

    Stepsok March 16th, 2020 at 11:46 am回复
  12. Stepsok

    Kamagra Vente En Ligne order cialis online Donating Blood And Amoxicillin Cialis Cheap Kamagra Uk Buy

    Stepsok March 16th, 2020 at 07:55 pm回复
  13. Janmit

    Viagra Falschungen Nebenwirkungen Cialis Viagra Online Kaufen Zollfrei Cialis For sale shipped ups isotretinoin acne discount medicine

    Janmit March 23rd, 2020 at 05:39 pm回复
  14. Janmit

    Buy Accutane Canada Buy Cialis Keflex Adult Dosage Weight Buy Cialis Priligy Dapoxetina Opinioni

    Janmit April 17th, 2020 at 07:47 pm回复
  15. Janmit

    Can You Buy Cialis In Cebu Pharmacy cheap cialis online pharmacy Propecia Cancer De Prostata Buy Cialis Cialis Sicuro

    Janmit April 27th, 2020 at 09:35 am回复
  16. unirtiern

    Cialis Super Active Plus Reviews https://agenericcialise.com/ - order cialis online Europa Kamagra Prescrizione order cialis Keflex Liquid Suspension Ingredients

    unirtiern June 30th, 2020 at 07:10 pm回复
  17. JerryHoini

    Знаете ли вы?
    Персонажу французской комедии о Фантомасе советские подростки подражали всерьёз.
    Водитель ледового комбайна стал звездой единственного матча НХЛ, в котором принял участие.
    Двое капитанов первого кругосветного плавания были казнены, следующего высадили на необитаемый остров.
    Возможно, что американцы уже в 1872 году вмешались в канадские выборы.
    Англичане купили заказанную португальцами рукопись голландца и бельгийца с изображениями монархов десяти королевств.

    arbeca

    JerryHoini July 4th, 2020 at 05:06 am回复
发表新评论