Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.Set;
- class Demonstrator {
- public static void main(String[] args) throws Exception {
- TokenBucketFiller tokenBucketFiller = new TokenBucketFiller(5);
- Set<Thread> threads = new HashSet<Thread>();
- Thread.sleep(10000);
- for (int i = 0; i < 20; i++) {
- Thread thread =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- tokenBucketFiller.consumeToken();
- } catch (InterruptedException ie) {
- }
- }
- });
- thread.setName("Thread " + i);
- threads.add(thread);
- }
- for (Thread thread : threads) {
- thread.start();
- }
- for (Thread thread : threads) {
- thread.join();
- }
- }
- }
- class TokenBucketFiller {
- private int maxCapacity;
- private int consumableTokens = 0;
- private long lastConsumedTime = System.currentTimeMillis();
- public TokenBucketFiller(int maxCapacity) {
- this.maxCapacity = maxCapacity;
- }
- public synchronized void consumeToken() throws InterruptedException {
- consumableTokens += (System.currentTimeMillis() - lastConsumedTime) / 1000;
- if (consumableTokens > maxCapacity) {
- consumableTokens = maxCapacity;
- }
- if (consumableTokens == 0) {
- Thread.sleep(1000);
- } else {
- consumableTokens--;
- }
- lastConsumedTime = System.currentTimeMillis();
- System.out.println(
- "Granting "
- + Thread.currentThread().getName()
- + " a token at time "
- + System.currentTimeMillis());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement