一个问题。这些 Runnables 是否需要在其前一个可运行对象完成后 N 秒或前一个被调度后 N 秒执行。
如果是后者,您可以连续安排和增加时间计数器。
int timeToWait = 2000;
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myObject, 2, 7, SECONDS);
for(int i = 1; i <= runnables.size(); i++){
scheduler.schedule(r, timeToWait * i, TimeUnit.MILLISECONDS);
}
前者有点棘手。你需要有可运行的计划它
final int timeToWait = 2000;
class SchedulingRunnable implements Runnable{
private final Iterator<Runnable> runnables;
private final ScheduledExecutorService scheduler
public SchedulingRunnable(Iterator<Runnable> rs, ScheduledExecutorService es){..}
public void run(){
runnables.next().run(); //assuming runnables.hasNext()
if(runnables.hasNext()){
scheduler.schedule(this, timeToWait, TimeUnit.MILLISECONDS);
}
}
}
ScheduledExecutorService scheduler =Executors.newScheduledThreadPool(1);
scheduler.schedule(new SchedulingRunnable(runnables.iterator(),schedule), timeToWait, TimeUnit.MILLISECONDS);
这个例子有一个包装器 Runnable 执行下一个可用的run
,然后在指定的等待时间之后安排下一个可用的。