信號量: Semaphore

 是一種計數器,用來保護一個或者多個共享資源的訪問。java

  Semaphore.acquire()                 
//獲取信號量,,當信號量的內部計數器變成0的時候,信號量將阻塞線程直到其被釋放。若是阻塞期間被中斷會拋出異常ui

Semaphore.acquireUninterruptibly(); 
//獲取信號量,當信號量的內部計數器變成0的時候,信號量將阻塞線程直到其被釋放。若是阻塞期間被中斷不會拋出異常this

Semaphore.release()                  //釋放信號量線程

 Semaphore.tryAcquire()               //試圖獲取信號量,若是能獲取就返回true,不能就返回falsecode

 Semaphore semaphore = new Semaphore(1, true);     建立信號量,計數器值爲1,且是公平模式資源

Semaphore semaphore = new Semaphore(1, false);    建立信號量,計數器值爲1,且是非公平模式it

 

static class Printer {
    private final Semaphore semaphore;

    Printer(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    public void print(String text) {
        try {
            this.semaphore.acquire();
            TimeUnit.SECONDS.sleep(1);
            System.out.println(text);
            TimeUnit.SECONDS.sleep(1);
            System.out.println(text);
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.semaphore.release();
        }

    }
}

public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(1, true);


    Stream.of("aaa", "bbb", "ccc").forEach(text -> {
        new Thread(() -> {
            Printer printer = new Printer(semaphore);
            printer.print(text);
        }).start();
    });

}
相關文章
相關標籤/搜索