介绍
一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。
示例
Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。例如,下面的类使用信号量控制对内容池的访问:
package com.chen.concurrent;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
SemaphoreTest semaphoreTest = new SemaphoreTest();
semaphoreTest.test01();
}
public void test01(){
Semaphore semaphore = new Semaphore(10);//定义有10个停车位
final Park park = new Park(semaphore);
//创建让车出停车场的线程
Thread t_letCarOut = new Thread(new Runnable() {
@Override
public void run() {
try {
while(true){
Thread.sleep(5000);
park.letGoout();
}
} catch (Exception e) {
// TODO: handle exception
}
}
});
t_letCarOut.start();
for(int i = 0;i < 100;i++){
park.letGoin("car"+i);
}
}
public class Park{
private Semaphore semaphore;
public Park(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void letGoin(String carName){
try {
System.out.println(carName+"存放汽车进入停车场");
if(semaphore.availablePermits() == 0){
System.out.println("现在车位不够了,无法进入停车场!");
}
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void letGoout(){
try {
System.out.println("放汽车出停车场");
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}