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
}
}
令牌桶算法示例(java实现)
最新推荐文章于 2024-07-27 04:44:45 发布
本文将深入探讨令牌桶算法,并提供一个详细的Java实现示例。令牌桶算法是一种流量整形和速率限制算法,常用于网络请求和服务端的流量控制。通过生成令牌并限制消费速度,该算法能有效地管理系统的资源利用率。
摘要由CSDN通过智能技术生成