Runnablesをスケジュールし、同じスレッドから順番に実行したいが、指定されたタイムアウトの後ではない。それを行う標準的な方法はありますか?ここ 指定されたタイムアウト後に1つのスレッドから複数のRunnableを実行する
は私のコードです:それはrun()
をだで
public class DelayedExecutor {
private final long _timeout;
private final List<Runnable> _tasks = new LinkedList<>();
private final ThreadFactory _factory;
private final Thread _supervisor;
public DelayedExecutor(long timeout, ThreadFactory factory) {
_timeout = timeout;
_factory = factory;
_supervisor = new Thread(new Runnable() {
@Override
public void run() {
while (_supervisor.isInterrupted()) {
try {
Thread.sleep(_timeout);
}
catch (InterruptedException e) {
if (_supervisor.isInterrupted())
break;
}
synchronized (_tasks) {
ArrayList<Runnable> prepared = new ArrayList<>(_tasks);
Collections.reverse(prepared);
execute(prepared);
_tasks.clear();
}
}
}
});
_supervisor.setDaemon(true);
_supervisor.start();
}
public void schedule(Runnable runnable) {
synchronized (_tasks) {
_tasks.add(runnable);
}
}
private void execute(final List<Runnable> tasks) {
_factory.newThread(new Runnable() {
@Override
public void run() {
for (Runnable runnable : tasks)
runnable.run();
}
});
}
}
これを順番に実行したいのですか? – Kiril
@Lirikはい。それ以前のタイムアウト(または他の何らかの条件)ではありません。すなわちn個の実行可能ファイルは既に待機している。 – aav
それは '以前ではありません'を修正してください –