Runnable
固定レートでスケジュールされたタスクをキャンセルScheduledExecutorService.scheduleAtFixedRate
し、キャンセルが呼び出されたときにタスクが実行されている場合に完了を待つ組み込みの方法はありますか?.
次の例を検討してください。
public static void main(String[] args) throws InterruptedException, ExecutionException {
Runnable fiveSecondTask = new Runnable() {
@Override
public void run() {
System.out.println("5 second task started");
long finishTime = System.currentTimeMillis() + 5_000;
while (System.currentTimeMillis() < finishTime);
System.out.println("5 second task finished");
}
};
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> fut = exec.scheduleAtFixedRate(fiveSecondTask, 0, 1, TimeUnit.SECONDS);
Thread.sleep(1_000);
System.out.print("Cancelling task..");
fut.cancel(true);
System.out.println("done");
System.out.println("isCancelled : " + fut.isCancelled());
System.out.println("isDone : " + fut.isDone());
try {
fut.get();
System.out.println("get : didn't throw exception");
}
catch (CancellationException e) {
System.out.println("get : threw exception");
}
}
このプログラムの出力は次のとおりです。
5 second task started
Cancelling task..done
isCancelled : true
isDone : true
get : threw exception
5 second task finished
共有揮発性フラグを設定するのが最も簡単なオプションのようですが、可能であれば避けたいと思います。
java.util.concurrent フレームワークには、この機能が組み込まれていますか?