令牌桶算法示例(java实现)

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

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值