Semaphore的基本理解
Semaphore英文翻译是信号灯的意思,在这个是信号量的意思
信号量主要用于两个目的,一个是用于多个共享资源的互斥使用,另一个是用于并发线程数的控制。
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);//模拟有3个停车位
for (int i = 0; i < 6; i++) { //模拟有6台汽车
new Thread(() -> {
try {
semaphore.acquire(); //获得了停车位的许可证,总数为3个
System.out.println(Thread.currentThread().getName() + "\t抢到了车位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "\t离开了车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release(); //释放了停车位的许可证,让别人可以获取,因为总共才3个
}
}, String.valueOf(i)).start();
}
}
}