一、Semaphore應用場景
- 主要用來控制系統中最大的併發執行的線程數,可以運用到需要進行限流的業務場景
二、一個簡單Demo搞懂Semaphore
public class MySemaphore {
/*Semaphore(10);相當於通過構造函數創造了10個供線程運行的位置*/
private static Semaphore semaphore = new Semaphore(10);
private static Thread[] threads = new Thread[20];
public static void main(String[] args) {
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(()->{
try {
/*當10個位置未滿時,當前線程則佔用一個位置,程序繼續往下執行,
* 當位置滿了當前線程則阻塞
* */
semaphore.acquire();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
/*
*此處相當於線程運行完後將位置歸還,歸還的位置可以繼續供其他線程調用
* 此處如果註釋的話相當於線程執行完後沒有讓出位置,因此執行完10個線程程序將會阻塞
* */
semaphore.release();
}
});
}
for (Thread thread : threads) {
thread.start();
}
}
}