3.1.3 允许多个线程同时访问:信号量

package 第三章.信号量;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
* Created by zzq on 2018/1/23.
*/
public class SimpoTest implements Runnable {
final Semaphore semaphore=new Semaphore(5);
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "-------获取执行权");
Thread.sleep(2000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(20);
final SimpoTest simpoTest=new SimpoTest();
for (int i = 0; i < 10; i++) {
executorService.submit(simpoTest);
}
executorService.shutdown();

}
}
原文地址:https://www.cnblogs.com/anxbb/p/8425529.html