/**
*
* @author chichaofan
*
*/
public class SimpleRateLimiter implements RateLimiter {
private AtomicLong atomPermit;
private long maxPermit;
private long interval;
private long lastTime;
public SimpleRateLimiter(long permit, int intervalTime, TimeUnit t) {
atomPermit = new AtomicLong(permit);
interval = t.toNanos(intervalTime);
maxPermit = permit;
}
@Override
public void acquire(long tryPermit) {
boolean rs = tryAcquire(tryPermit);
if (rs)
return;
boolean interrupted =false;
try{
long end = lastTime + interval;
while (true) {
try {
NANOSECONDS.sleep((end - System.nanoTime()));
rs = tryAcquire(tryPermit);
if (rs)
return;
} catch (InterruptedException e) {
interrupted = true;
}
}
}finally{
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
@Override
public boolean tryAcquire(long tryPermit) {
if (System.nanoTime() > (lastTime + interval)) {
atomPermit.set(maxPermit);
lastTime = System.nanoTime();
}
long value = atomPermit.get();
boolean rs = false;
while (value > 0 && !rs) {
rs = atomPermit.compareAndSet(value, value - tryPermit);
value = atomPermit.get();
}
return rs;
}
public static void main(String[] args) {
final RateLimiter r = new SimpleRateLimiter(2, 1000, TimeUnit.MILLISECONDS);
new Thread(new Runnable() {
public void run() {
while (true) {
r.acquire(1);
System.out.println(Thread.currentThread().getName()+"true");
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (true) {
r.acquire(1);
System.out.println(Thread.currentThread().getName()+"true");
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (true) {
r.acquire(1);
System.out.println(Thread.currentThread().getName()+"true");
}
}
}).start();
}
}
Java并发限流工具
最新推荐文章于 2024-09-16 07:00:00 发布