Semaphore官方文档
一、使用信号量实现线程间的通信
/**
* Demo:使用信号量实现线程间通信*/
public class SemaphoreDemo {
public static void main(String[] args) {
// 线程池。信号量通常都是针对多个线程,直接使用线程池实现
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(2);//每次允许2个线程获得许可
// 模拟20个客户端访问
for (int i = 0; i < 20; i++) {
final int num = i;
Runnable run = new Runnable() {
public void run() {
try {
// 获取许可
semaphore.acquire();
System.out.println("Accessing: " + num);
Thread.sleep(3000);
// 访问完后,释放
semaphore.release();
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
}
}
二、信号量实现限流