
java semaphore是什么?让我们一起来了解一下吧!
java semaphore是java程序中的一种锁机制,叫做信号量。它的作用是操纵并且访问特定资源的线程数量,允许规定数量的多个线程同时拥有一个信号量。

相关的方法有以下几个:
1.void acquire() :从信号量获取一个允许,若是无可用许可前将会一直阻塞等待
2. boolean tryAcquire():从信号量尝试获取一个许可,如果无可用许可,直接返回false,不会阻塞
3. boolean tryAcquire(int permits, long timeout, TimeUnit unit):
在指定的时间内尝试从信号量中获取许可,如果在指定的时间内获取成功,返回true,否则返回false
4.int availablePermits(): 获取当前信号量可用的许可
semaphore构造函数:
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}实战举例,具体步骤如下:
public static void main(String[] args) {
//允许最大的登录数
int slots=10;
ExecutorService executorService = Executors.newFixedThreadPool(slots);
LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
//线程池模拟登录
for (int i = 1; i {
if (loginQueue.tryLogin()){
System.out.println("用户:"+num+"登录成功!");
}else {
System.out.println("用户:"+num+"登录失败!");
}
});
}
executorService.shutdown();
System.out.println("当前可用许可证数:"+loginQueue.availableSlots());
//此时已经登录了10个用户,再次登录的时候会返回false
if (loginQueue.tryLogin()){
System.out.println("登录成功!");
}else {
System.out.println("系统登录用户已满,登录失败!");
}
//有用户退出登录
loginQueue.logout();
//再次登录
if (loginQueue.tryLogin()){
System.out.println("登录成功!");
}else {
System.out.println("系统登录用户已满,登录失败!");
} }
class LoginQueueUsingSemaphore{
private Semaphore semaphore;
/**
*
* @param slotLimit
*/
public LoginQueueUsingSemaphore(int slotLimit){
semaphore=new Semaphore(slotLimit);
}
boolean tryLogin() {
//获取一个凭证
return semaphore.tryAcquire();
}
void logout() {
semaphore.release();
}
int availableSlots() {
return semaphore.availablePermits();
}
}以上就是小编今天的分享了,希望可以帮助到大家。
