Semaphore可以控制同时访问的线程个数,通过 acquire() 获取一个许可(若无许可能够获得,则会一直等待,直到获得许可),如果没有就等待,而 release() 释放一个许可(注意,在释放许可之前,必须先获获得许可)。
package com.test.concurrent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.concurrent.*;
@Slf4j
public class TestSemaphore {
private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5,
new BasicThreadFactory.Builder().namingPattern("test-schedule-pool-%d").daemon(false).build());
private static Semaphore semaphore = new Semaphore(3);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String seconds = String.valueOf(i);
executorService.submit(() -> {
try {
semaphore.acquire();
TimeUnit.SECONDS.sleep(2);
semaphore.release();
log.info("线程[{}-{}]占用了[2s]后释放", Thread.currentThread().getName(), seconds);
} catch (Exception ex) {
ex.printStackTrace();
}
});
}
}
}