指定秒内的最大线程调用
max thread calls in specified seconds
我想在 10 秒内将方法的调用次数限制为 5 次。将有来自不同线程的方法调用。在那段时间过去后,我希望重置该方法的计数器,以便在接下来的 10 秒内,可以再进行 5 次调用,这将继续进行。执行此操作的好方法是什么?
谢谢
也许可以使用 Semaphore 和 Timer
来释放代币:
public class RateLimitedTask() {
private final Timer timer = new Timer();
private final Semaphore semaphore;
private final Runnable task;
public RateLimitedTask(
final Runnable task,
final int limit,
final int delay
) {
this.task = task;
semaphore = new Semaphore(limit);
timer.schedule(new TimerTask() {
@Override
public void run() {
semaphore.release(limit);
}
}, delay*1000, delay*1000);
}
public void run() throws InterruptedException {
semaphore.acquire();
task.run();
}
}
我想在 10 秒内将方法的调用次数限制为 5 次。将有来自不同线程的方法调用。在那段时间过去后,我希望重置该方法的计数器,以便在接下来的 10 秒内,可以再进行 5 次调用,这将继续进行。执行此操作的好方法是什么?
谢谢
也许可以使用 Semaphore 和 Timer
来释放代币:
public class RateLimitedTask() {
private final Timer timer = new Timer();
private final Semaphore semaphore;
private final Runnable task;
public RateLimitedTask(
final Runnable task,
final int limit,
final int delay
) {
this.task = task;
semaphore = new Semaphore(limit);
timer.schedule(new TimerTask() {
@Override
public void run() {
semaphore.release(limit);
}
}, delay*1000, delay*1000);
}
public void run() throws InterruptedException {
semaphore.acquire();
task.run();
}
}