一、获取单个许可
信号量设置为3,每次获取1个许可,那么就可以连续获得3个许可。
如下面的信号量Demo
@Slf4j
public class SemaphoreExample1 {
private static int threadCount = 20;
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
for(int i = 0; i < threadCount; i++){
final int threadNum = i;
exec.execute(()->{
try {
semaphore.acquire();//获得一个许可
test(threadNum);
semaphore.release();//释放一个许可
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
exec.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
log.info("{}", threadNum);
Thread.sleep(1000);
}
}
打印结果如下。信号量设置为3。 差不多每隔1秒钟打印3条数据。

二、获得多个许可
线程数为20,信号量为3,每次获得3个许可。相当于单线程。
@Slf4j
public class SemaphoreExample2 {
private static int threadCount = 20;
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
for(int i = 0; i < threadCount; i++){
final int threadNum = i;
exec.execute(()->{
try {
semaphore.acquire(3);//获得3个许可, 信号量为3,相当于单线程执行
test(threadNum);
semaphore.release(3);//释放3个许可
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
exec.shutdown();
}
private static void test(int threadNum) throws InterruptedException {
log.info("{}", threadNum);
Thread.sleep(1000);
}
}
原文:https://www.cnblogs.com/linlf03/p/12748093.html