信号灯主要用于两个目的,一个是用于多个共享资源的互斥使用,另一个是用于并发线程数的控制
示例代码:举例:争抢车位问题
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore=new Semaphore(3); //模拟3个停车位
for (int i = 1; i <=6 ; i++) { //模拟6部汽车
new Thread(()->{
try {
try {semaphore.acquire();}catch (InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t 抢到车位");
//暂停一会线程
try {TimeUnit.SECONDS.sleep(3);}catch (InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t 停车3秒之后离开车位");
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
运行结果:
1 抢到车位
2 抢到车位
3 抢到车位
1 停车3秒之后离开车位
2 停车3秒之后离开车位
4 抢到车位
5 抢到车位
3 停车3秒之后离开车位
6 抢到车位
5 停车3秒之后离开车位
4 停车3秒之后离开车位
6 停车3秒之后离开车位
上述代码,semaphore.acquire() 一次 消费一个停车位,停车位减1,semaphore.release() 一次 释放一个停车位,停车位恢复一个,有效的解决了共享资源的互斥使用,控制了并发的线程数