java自带的Semaphore类
private Semaphore semaphore = new Semaphore(1);
@SneakyThrows
@RequestMapping(value = "/02",method = RequestMethod.GET)
public void test2(){
int id = semaphore.availablePermits();
log.info("===========当前可用资源{}",id);
if(id > 0){
log.info("===========抢到了资源");
try {
semaphore.acquire(1);
log.info("===========资源正在被使用");
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
semaphore.release(1);
log.info("===========释放一个资源");
}
}else {
log.info("===========资源已被占用,稍后再试");
}
}
输出结果:
===========当前可用资源1
===========抢到了资源
===========资源正在被使用
===========当前可用资源0
===========资源已被占用,稍后再试
===========当前可用资源0
===========资源已被占用,稍后再试
===========当前可用资源0
===========资源已被占用,稍后再试
===========当前可用资源0
===========资源已被占用,稍后再试
===========当前可用资源0
===========资源已被占用,稍后再试
===========当前可用资源0
===========资源已被占用,稍后再试
===========释放一个资源
版权声明:本文为qq_15273441原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。