semaphore:信号量,又可称为限流器,可以控制线程的并发量,初始化的之后指定令牌数。
Semaphore 管理了一系列的许可证,也就是令牌机制。每个线程进来,调用acquire()获得令牌,
若无法获得令牌,放到同步队列AQS中并阻塞。如果获得令牌,执行方法后,调用release()释放令牌,
其他线程才再次争抢令牌。
拥有的方法如下:
acquire() :获取令牌
release() :释放令牌
实例代码如下:
public class SemaPhoreDemo {
static class Car extends Thread{
private int num;
private Semaphore semaphore;
public Car(Semaphore semaphore,int num){
this.num=num;
this.semaphore=semaphore;
}
public void run(){
try {
semaphore.acquire();
System.out.println("第"+num+"占一个车位");
Thread.sleep(200);
System.out.println("第"+num+"开走了");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(5);
for (int i = 1; i < 11; i++) {
new Car(semaphore,i).start();
}
}
}
执行结果如下:
第1占一个车位
第2占一个车位
第3占一个车位
第4占一个车位
第5占一个车位
第2开走了
第6占一个车位
第1开走了
第7占一个车位
第3开走了
第8占一个车位
第5开走了
第9占一个车位
同一时刻,只能有5个线程获得令牌执行,其他线程阻塞,只有又令牌被释放,其他线程才会执行。