我有一个监听外部事件的对象。收到事件后,我的对象需要执行一个任务(一个Runnable)。但是,有一个限制:
一旦任务开始执行,我不应该开始其他任务(我可以忽略它们),直到原始任务完成并且在那之后经过一定的时间(节流)。
这是使用semaphore的建议实现:
public class Sample {
private final Semaphore semaphore = new Semaphore(1);
private final ScheduledExecutorService executor;
public Sample(ScheduledExecutorService executor) {
this.executor = executor;
}
public void tryRun() {
if (semaphore.tryAcquire()) {
try {
executor.submit(
new Runnable() {
@Override
public void run() {
try {
doIt();
} finally {
try {
executor.schedule(
new Runnable() {
@Override
public void run() {
semaphore.release();
}
},
1,
TimeUnit.MINUTES
);
} catch (Throwable t) {
semaphore.release();
}
}
}
}
);
} catch (Throwable t) {
semaphore.release();
}
}
}
private void doIt() {
// the exact task executing logic is here
}
}
代码对我来说似乎太冗长了。有没有更好的方法来做到这一点?
PS 另一个限制是ScheduledExecutorService是我对外部执行程序的唯一接口,我无法在我的对象中启动我自己的线程/执行程序