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

来源:互联网 发布:手链饰品店淘宝 编辑:程序博客网 时间:2024/05/24 02:31

//设置信号量的容量为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


阅读全文
0 0
原创粉丝点击