JUC - Semaphore
信号量主要用于两个目的:
- 一个是用于多个共享资源的互斥使用
- 一个用于并发线程数的控制。
例子:抢车位
package com.test.mianshi;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Semaphore 与 CountDownLatch及CyclicBarrier 更具有伸缩性,可有重复利用资源
* 抢车位
*/
public class SemaphoreDemo {
public static void main(String[] args) {
// 模拟三个车位
Semaphore semaphore = new Semaphore(3);
// 模拟6辆车同时来抢车位
for (int i = 0; i < 6; i++) {
new Thread(()->{
try {
// 抢到资源
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " 抢到车位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+ " 离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
// 释放资源
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
控制台打印结果:
0 抢到车位
1 抢到车位
3 抢到车位
0 离开车位
4 抢到车位
1 离开车位
2 抢到车位
3 离开车位
5 抢到车位
4 离开车位
2 离开车位
5 离开车位