fork(1) download
  1.  
  2.  
  3. import java.util.Timer;
  4. import java.util.TimerTask;
  5. import java.util.function.IntConsumer;
  6.  
  7.  
  8. public class Main {
  9.  
  10.  
  11. private static class CountDownTimer extends Timer {
  12.  
  13. private IntConsumer onCountDown;
  14. private Runnable onCountZero;
  15.  
  16. public CountDownTimer(IntConsumer onCountDown, Runnable onCountZero) {
  17.  
  18. this.onCountDown = onCountDown;
  19. this.onCountZero = onCountZero;
  20. }
  21.  
  22. public TimerTask countDown(int count, long period) {
  23.  
  24. Task task = new Task(count);
  25. scheduleAtFixedRate(task, 0L, period);
  26.  
  27. return task;
  28. }
  29.  
  30. private class Task extends TimerTask {
  31.  
  32. private int count;
  33.  
  34. public Task(int count) {
  35. this.count = count;
  36. }
  37.  
  38. @Override
  39. public void run() {
  40.  
  41. onCountDown.accept(count);
  42.  
  43. if (--count < 0) {
  44. Task.this.cancel();
  45. onCountZero.run();
  46. }
  47. }
  48. }
  49. }
  50.  
  51.  
  52. public static void main(String[] args) throws Exception {
  53.  
  54. // カウントダウン時の処理 (count: int)
  55. IntConsumer onCountDown = count -> {
  56. System.out.println(count);
  57. };
  58.  
  59. // カウントゼロ時の処理
  60. Runnable onCountZero = () -> {
  61. System.out.println("Game Over");
  62. };
  63.  
  64. // Timer を開始する
  65. CountDownTimer timer = new CountDownTimer(onCountDown, onCountZero);
  66.  
  67. // カウントの初期値とカウントダウン間隔 (ミリ秒)
  68. int count = 10;
  69. long period = 1000L;
  70.  
  71. // カウントダウン開始 (所要時間 10 秒)
  72. TimerTask task = timer.countDown(count, period);
  73.  
  74. // 開始後 5 秒間待機
  75. Thread.sleep(5000L);
  76.  
  77. // カウントダウンを途中で止めてみる
  78. task.cancel();
  79.  
  80. // その後 5 秒間待機
  81. Thread.sleep(5000L);
  82.  
  83. // カウントダウン開始 (所要時間 10 秒)
  84. timer.countDown(count, period);
  85.  
  86. // 開始後 12 秒間待機
  87. Thread.sleep(12000L);
  88.  
  89. // プログラム終了時に必要な処理
  90. timer.cancel();
  91. }
  92. }
  93.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty