Semaphore使用方法

  /*    * 控制線程執行數    * 原理:    * 在信號量上咱們定義兩種操做:    * acquire(獲取)當一個線程調用acquire操做時,它要麼經過成功獲取信號量(信號量減一),    * 要麼一直等下去,知道有線程釋放信號量,或超時。    * release(釋放)實際上會將信號量的值加1,而後喚醒等等待的線程。    * 信號量主要用於兩個目的,一個是用於多個共享資源的互斥使用,另外一個用於併發線程數控制    * */    Semaphore semaphore=new Semaphore(3);    for(int i=1;i<=6;i++){        new Thread(()->{            try {                semaphore.acquire();            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println(Thread.currentThread().getName()+"\t搶到了");            try {                TimeUnit.SECONDS.sleep(3);                System.out.println(Thread.currentThread().getName()+"\t離開了");            } catch (InterruptedException e) {                e.printStackTrace();            }finally {                semaphore.release();            }        },String.valueOf(i)).start();    }}
相關文章
相關標籤/搜索