토큰버킷

2026년 2월 19일 11:23분

package com.jesusbornd.exodus;

public class Exodus_34_Chapter_Lv3 {

    public static class TokenBucket {
        private final int capacity;
        private int tokens;

        public TokenBucket(int capacity) {
            this.capacity = capacity;
            this.tokens = capacity;
        }

        public boolean tryConsume(int n) {
            if (n <= 0) return true;
            if (tokens < n) return false;
            tokens -= n;
            return true;
        }

        public void refill() {
            tokens = capacity;
        }

        public int remaining() {
            return tokens;
        }
    }

    public static void main(String[] args) {
        TokenBucket mercy = new TokenBucket(3);

        System.out.println(mercy.tryConsume(1));
        System.out.println(mercy.remaining());

        System.out.println(mercy.tryConsume(2));
        System.out.println(mercy.remaining());

        System.out.println(mercy.tryConsume(1));
        System.out.println(mercy.remaining());

        mercy.refill();
        System.out.println(mercy.remaining());
    }
}

class TokenBucket:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.tokens = capacity

    def try_consume(self, n: int) -> bool:
        if n <= 0:
            return True
        if self.tokens < n:
            return False
        self.tokens -= n
        return True

    def refill(self):
        self.tokens = self.capacity

    def remaining(self) -> int:
        return self.tokens

mercy = TokenBucket(3)

print(mercy.try_consume(1))
print(mercy.remaining())

print(mercy.try_consume(2))
print(mercy.remaining())

print(mercy.try_consume(1))
print(mercy.remaining())

mercy.refill()
print(mercy.remaining())

Comments

아직 댓글이 없습니다!


Search

← 목록으로