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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章