信号量主要有两种用途:
1. 保护一个重要(代码)部分防止一次超过 N 个线程进入。
如果你将信号量用于保护一个重要部分,试图进入这一部分的代码通常会首先尝试获得一个
许可,然后才能进入重要部分(代码块),执行完之后,再把许可释放掉。比如这样:
public class SemphoreTest {
private static final int THREAD_COUNT = 30;
private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
private static Semaphore s = new Semaphore(10);
private static int count = 0;
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
s.acquire();
System.out.println(++count+"save data");
// s.release();
}catch (InterruptedException e){
}