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 {
- TokenBucketFilter tokenBucketFiller = TokenBucketFillerFactory.create(1);
- Set<Thread> threads = new HashSet<Thread>();
- for (int i = 0; i < 10; 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();
- }
- }
- }
- public abstract class TokenBucketFilter {
- public void consumeToken() throws InterruptedException {}
- }
- class TokenBucketFillerFactory {
- private TokenBucketFillerFactory() {}
- public static TokenBucketFilter create(int maxCapacity) {
- MultiThreadedTokenBucketFiller tokenBucketFiller =
- new MultiThreadedTokenBucketFiller(maxCapacity);
- tokenBucketFiller.initializeProducer();
- return tokenBucketFiller;
- }
- private static class MultiThreadedTokenBucketFiller extends TokenBucketFilter {
- private int maxCapacity;
- private int consumableTokens = 0;
- public MultiThreadedTokenBucketFiller(int maxCapacity) {
- this.maxCapacity = maxCapacity;
- }
- public void initializeProducer() {
- Thread producer = new Thread(() -> {
- produceTokens();
- });
- producer.setDaemon(true);
- producer.start();
- }
- private void produceTokens() {
- while(true) {
- synchronized(this) {
- if(consumableTokens < maxCapacity) {
- consumableTokens++;
- }
- this.notify();
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException ie) {
- }
- }
- }
- public void consumeToken() throws InterruptedException {
- synchronized (this) {
- while (consumableTokens == 0) {
- this.wait();
- }
- consumableTokens--;
- }
- System.out.println(
- "Granting "
- + Thread.currentThread().getName()
- + " a token at time "
- + (System.currentTimeMillis() / 1000));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement