Semaphore

1.介紹

信號量爲多線程協作提供了更爲強大的控制方法。廣義上說信號量是對鎖的擴展,可以指定多個線程同時訪問某一資源。

2. 構造方法

	public Semaphore(int permits) {
        sync = new NonfairSync(permits);
    }
    
    public Semaphore(int permits, boolean fair) {
        sync = fair ? new FairSync(permits) : new NonfairSync(permits);
    }

3. 主要方法

public void acquire() throws InterruptedException;
public void acquireUninterruptibly();
public void acquire(int permits) throws InterruptedException;
public boolean tryAcquire() ;
public boolean tryAcquire(long timeout, TimeUnit unit);
public boolean tryAcquire(int permits);
public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
        throws InterruptedException;
public void release(int permits);

acquire()方法會嘗試獲得一個准入許可,若無法獲得,則線程會等待,直到有一個線程釋放一個許可或者當前線程被中斷

發佈了311 篇原創文章 · 獲贊 114 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章