脚本宝典收集整理的这篇文章主要介绍了多线程之Semaphore登录限流示例,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
public static void main(String[] args) { //允许最大的登录数 int slots=10; ExecutorService executorService = Executors.newFixedThreadPool(slots); LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots); //线程池模拟登录 for (int i = 1; i <= slots; i++) { final int num=i; executorService.execute(()->{ 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(); } }
以上是脚本宝典为你收集整理的多线程之Semaphore登录限流示例全部内容,希望文章能够帮你解决多线程之Semaphore登录限流示例所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。