目录
一、AQS组件——信号量Semaphore
1. 信号量(Semaphore
)介绍:
- 作用:用于保证同一时间并发访问线程的数目。
- 信号量在操作系统中是很重要的概念,Java并发库里的
Semaphore
就可以很轻松的完成类似操作系统信号量的控制; Semaphore
使用acquire
方法和release
方法来实现控制;- 在数据结构中我们学过链表,链表正常是可以保存无限个节点的,而
Semaphore
可以实现有限大小的列表。
2.使用场景
仅能提供有限访问的资源。比如数据库连接。
二、信号量(Semaphore
)的使用
1.允许单一许可场景
期望:有20个线程,每次只允许3个线程同时执行test()
方法,具体代码如下:
@Slf4j
public class SemaphorehExample1 {
private static final int threadCount = 200;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
//实例化Semaphore,并设置允许的并发数
final Semaphore semaphore = new Semaphore(3);
for (int i=0; i<threadCount; i++){
final int threadNum = i;
executorService.execute(()->{
try {
semaphore.acquire(); //拿到一个许可,执行后面的test()语句
test(threadNum);
semaphore.release();//释放一个许可
}catch (Exception e){
log.error("exception",e);
}finally {
}
});
}
executorService.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
log.info("{}",threadNum);
Thread.sleep(1000);
}
}
执行结果部分内容如下:
...
23:06:41.896 [pool-1-thread-2] INFO com.mmall.concurrency.example.aqs.SemaphorehExample1 - 1
23:06:41.896 [pool-1-thread-1] INFO com.mmall.concurrency.example.aqs.SemaphorehExample1 - 0
23:06:41.903 [pool-1-thread-3</