谷歌guava包里提供了内存限流工具RateLimiter
示例:
// 创建一个限流器,该配置可以每秒均匀产生4个令牌
RateLimiter rateLimiter = RateLimiter.create(4);
@Test
public void flowLimitTest() throws InterruptedException {
List<Thread> threads = new ArrayList<>();
// 生成10个线程运行
for(int i = 0 ; i < 10 ; i ++){
threads.add(new Thread(() -> {
for(;;){
// 抢1个令牌,抢不到阻塞
rateLimiter.acquire();
System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis());
}
}));
threads.get(i).start();
}
threads.get(0).join();
}
运行结果
Thread-10 - 1588868393118
Thread-9 - 1588868393369
Thread-8 - 1588868393618
Thread-7 - 1588868393868
Thread-6 - 1588868394118
Thread-4 - 1588868394368
Thread-5 - 1588868394619
Thread-3 - 1588868394869
Thread-2 - 1588868395119
Thread-1 - 1588868395369
Thread-10 - 1588868395619
Thread-9 - 1588868395869
Thread-8 - 1588868396119
Thread-7 - 1588868396368
Thread-6 - 1588868396619
Thread-4 - 1588868396869
Thread-5 - 1588868397120
Thread-3 - 1588868397370
Thread-2 - 1588868397620
Thread-1 - 1588868397869
全部评论