java semaphore
- IT科技
- 关注:2.86W次
<link rel="stylesheet" href="https://js.how234.com/3f0e869d6d/260484806ecf5e3f60c68fd45fc34391a2/260993986ac4/2615a99b7dd2.css" type="text/css" /><link rel="stylesheet" href="https://js.how234.com/3f0e869d6d/260484806ecf5e3f60c68fd45fc34391a2/260993986ac4/2615be9c6ada531262c882c854df.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><style>pre{overflow-x: auto}</style>
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
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(); }}
- 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/itkeji/yxvjrk.html