import java.util.concurrent.Semaphore;
/**
* @Description 使用Semaphore 构建一个限流器
*/
public class Restrictor {
final private Semaphore semaphore;
/**
* 初始化限制并发流量的大小
* @param size
*/
public Restrictor(int size) {
semaphore = new Semaphore(size);
}
public void exec() throws InterruptedException {
//先抢占一个位置 抢占不到就阻塞等待
semaphore.acquire();
try {
//下面就是业务代码
} finally {
//释放位置
semaphore.release();
}
}
}