Guava

RateLimiter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
RateLimiter rateLimiter = RateLimiter.create(10);
for (int i = 0; i < 20; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
int cnt = 0;
while (true) {
if (rateLimiter.tryAcquire()) {
cnt++;
System.out.println("thread: " + finalI + " cnt: " + cnt);
}
}
}
}).start();
}
Thread.sleep(1000 * 100 * 1000);

源码流程图: