您的位置:首页 > 编程语言 > Java开发

【Java开发】使用Semaphore控制资源访问并发量

2017-10-15 14:55 573 查看
//设置信号量的容量为10,超过10后,则在队列排队。
//tryAcquire()尝试向信号器获取一个信号量
//release()释放信号量
static final int productThreadNum=10;
static final int productTimeOut=50;
static final int productQueueLenth=1000;
static final Semaphore productSemaphore=new Semaphore(productThreadNum,true);
public static boolean tryAcquireProduct() throws InterruptedException{
int count=productSemaphore.getQueueLength();
log.info("当前等待线程:{}",count);
if(count>productQueueLenth){
throw new LogicalException("购买人数过多,请稍后重试");
}
return productSemaphore.tryAcquire(productTimeOut, TimeUnit.SECONDS);
}
public static void releaseProuct(){
productSemaphore.release();
}



https://github.com/jerrik123 https://gitee.com/huangyong
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: