Semaphore基本使用及原理
文章目录
在前面的文章中我们学习了
AQS
、
ReentrantLock
和
CountDownLatch
的原理。在今天的文章中我们再学习一个
JUC
下的工具类-
Semaphore
。
今天的文章中我们会先介绍下Semaphore
的使用,然后通过源码来学习下其是如何实现的。
1 什么是Semaphore
Semaphore(信号量)
,是JUC
包下的一个工具类,我们可以通过其限制执行的线程数量,达到限流的效果。
当一个线程执行时先通过其方法进行获取许可操作,获取到许可的线程继续执行业务逻辑,当线程执行完成后进行释放许可操作,未获取达到许可的线程进行等待或者直接结束。
2 基本使用
Semaphore
的使用也是比较简单的,我们创建一个Runnable
的子类,如下:
private static class MyRunnable implements Runnable {
// 成员属性 Semaphore对象
private final Semaphore semaphore;
public MyRunnable(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void run() {
String threadName = Thread.currentThread().getName();
// 获取许可
boolean acquire = semaphore.tryAcquire();
// 未获取到许可 结束
if (!acquire) {
System.out.println("线程【" + threadName + "】未获取到许可,结束");
return;
}
// 获取到许可
try {
System.out.println("线程【" + threadName + "】获取到许可");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放许可
semaphore.release();
System.out.println("线程【" + threadName + "】释放许可");
}
}
}
测试方法如下:
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
for (int i = 0; i <= 10; i ++) {
MyRunnable runnable = new