一、Semaphore应用场景
- 主要用来控制系统中最大的并发执行的线程数,可以运用到需要进行限流的业务场景
二、一个简单Demo搞懂Semaphore
public class MySemaphore {
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 {
semaphore.acquire();
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
});
}
for (Thread thread : threads) {
thread.start();
}
}
}