semphore作用
- Semaphore 字面意思是信号量的意思,它的作用是控制访问特定资源的线程数目
semphore构造函数
/**
* permits:许可线程的数量,代表同一时间,最多允许permits个线程执行acquire() 和release() 之间 * 的代码。同时内部变量state许可量的值等于permits
*/
public Semaphore(int permits) {
//默认非公平锁
sync = new NonfairSync(permits);
}
/**
* fair:表示公平性
* False:表示非公平信号量,即线程启动的顺序与调用semaphore.acquire() 的顺序无关,也就是线程先 * 启动了并不代表先获得 许可。
* True:公平信号量,即线程启动的顺序与调用semaphore.acquire() 的顺序有关,也就是先启动的线程 * 优先获得许可
*/
public Semaphore(int permits, boolean fair) {
//根据fair值判断公平锁或非公平锁
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
semphore核心方法
/**
* 获取1个许可,当获取不到时线程阻塞直到获取到许可
*/
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
*释放一个许可
*/
public void release() {
sync.releaseShared(1);
}
/**
* 获取permits个许可,当获取不到时线程阻塞直到获取到许可
*/
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
/**
* 释放permits个许可
*/</