Semaphore 是一个计数信号量,必须由获取它的线程释放。
常用于限制可以访问某些资源的线程数量,例如通过 Semaphore 限流。
public class SemaphoreDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(2);//信号量,只允许 2个线程同时访问
for (int i = 0; i < 10; i++) {
final long num = i;
exec.submit(new Runnable(){
public void run() {
try {
semp.acquire();
System.out.println("Accessing: " + num);
Thread.sleep(new Random().nextInt(6000)); // 模拟随机执行时长
semp.release();
System.out.println("Release..." + num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
// 退出线程池
exec.shutdown();
}
}
运行结果:
就这么简单、通俗易懂。