Semaphore是啥?
贴个官方解释:
Semaphore用于限制可以访问某些资源(物理或逻辑的)的线程数目,其维护了一个许可证集合,有多少资源限制就维护多少许可证集合,假如这里有N个资源,那就对应于N个许可证,同一时刻也只能有N个线程访问。一个线程获取许可证就调用acquire方法,用完了释放资源就调用release方法。
举例
举个生活中的例子:
某餐厅只有3张餐桌,而当前需要接待的客人有6桌,那么就需要领号排队,结束一桌进去一桌,此处餐桌就相当于Semaphore的许可证。
通过代码实现上述过程:
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
Semaphore semaphore = new Semaphore(3);
for(int i=0; i<6; i++){
Runnable runnable = new Runnable() {
@Override
public void run() {
try{
// 获取令牌
System.out.println(System.currentTimeMillis() + ": " + Thread.currentTh