public class test {
volatile static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) throws IOException {
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(() -> {
System.out.println("正在加令牌: 4");
count.addAndGet(4);
}, 0, 10, TimeUnit.SECONDS);
Object obj = new Object();
for (int i = 0; i < 2; i++) {
new Thread(() -> {
while (true) {
minus();
}
}).start();
}
System.in.read();
}
public static void minus() {
ReentrantLock lock = new ReentrantLock(true);
lock.lock();
try {
Thread.sleep(1000);
if (count.intValue() > 0) {
System.out.println(Thread.currentThread() + " 正在消耗令牌!");
count.decrementAndGet();
} else {
System.out.println(Thread.currentThread() + " 去拿令牌时,令牌桶中的令牌用完了!");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
简易令牌桶算法的实现
最新推荐文章于 2024-09-01 17:27:14 发布