构造方法
Semaphore(int permits)
Semaphore(int permits, boolean fair)
信号量主要逻辑方法如下:
public void acquire() throws InterruptedException
public void acquireUninterruptibly()
public boolean tryAcquire()
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException
public void release()
- acquire()方法尝试获得一个准入的许可;若无法获得,则线程会等待,直到有线程释放一个许可或者当前线程被中断;
- acquireUninterruptibly()方法和acquire()方法类似,只是不响应中断;
- tryAcquire()方法尝试获得一个许可,如果成功返回true,失败返回false,不会进行等待,立即返回;
- release()方法用于在线程访问资源结束后释放一个许可,以使其他等待许可的线程可以进行资源访问;
public class SemaphoreDemo implements Runnable {
private final Semaphore semaphore = new Semaphore(5);
@Override
public void run() {
try {
semaphore.acquire();
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + ":done!");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(20);
final SemaphoreDemo sd = new SemaphoreDemo();
for(int i = 0; i < 20; i++) {
exec.submit(sd);
}
}
}
声明了一个包含5个许可的信号量,同时可以有5个线程进入临界区;
输出以5个线程一组为单位,依次打印信息;
pool-1-thread-3:done!
pool-1-thread-1:done!
pool-1-thread-2:done!
pool-1-thread-4:done!
pool-1-thread-5:done!
pool-1-thread-6:done!
pool-1-thread-9:done!
pool-1-thread-8:done!
pool-1-thread-7:done!
pool-1-thread-10:done!
pool-1-thread-12:done!
pool-1-thread-15:done!
pool-1-thread-14:done!
pool-1-thread-11:done!
pool-1-thread-13:done!
pool-1-thread-17:done!
pool-1-thread-18:done!
pool-1-thread-16:done!
pool-1-thread-19:done!
pool-1-thread-20:done!