import java.util.concurrent.atomic.AtomicInteger;
public class TokenTask {
private final int capacity; //令牌桶容量
private final int refillRate;//令牌桶补充速率
private final AtomicInteger tokens;//使用原子类来保证线程安全,表示当前令牌中的令牌数量。
private long lastRefillTimestamp;//表示上次令牌桶补充的时间戳
public TokenTask(int capacity, int refillRate) {
this.capacity = capacity;
this.refillRate = refillRate;
this.tokens = new AtomicInteger(capacity);
this.lastRefillTimestamp = System.nanoTime();
}
public synchronized boolean tryConsume(int numTokens){
refill();
if(tokens.get()>=numTokens){
tokens.addAndGet(-numTokens);
return true;
}else {
return false;
}
}
private void refill(){
long now = System.nanoTime();
long refillTokens = (now - lastRefillTimestamp) / 1_000_000_000 * refillRate;
if(refillTokens>0){
int newTokens=Math.min(capacity,tokens.get()+(int)refillTokens);
tokens.set(newTokens);
lastRefillTimestamp=now;
}
}
public static void main(String[] args) throws InterruptedException {
TokenTask tokenTask = new TokenTask(10, 1);
//模拟
System.out.println(tokenTask.tryConsume(1)); //true
System.out.println(tokenTask.tryConsume(10));
System.out.println(tokenTask.tryConsume(8));
Thread.sleep(3000);
System.out.println(tokenTask.tryConsume(1)); // true
}
}
05-05
03-31
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交