[编辑] 下面的代码没有使用“scheduleAtFixedRate”,所以它的结论可能是错误的......(永远不要相信互联网上的那些人:)
【原创】我偏爱和我一样懒的人:
计时器等待。它一次只能运行一个任务。
(** 使用 java-1.8.0-openjdk 测试)
代码(scala,但它正在使用 Java 计时器):
import java.util.{Timer, TimerTask}
object O {
val iGen = new AtomicInteger()
def main(args: Array[String]): Unit = {
val timer = new Timer()
val timerTask = new TimerTask {
override def run(): Unit = {
val tid = iGen.incrementAndGet()
println(s"--- task #$tid started")
Thread sleep(5000)
println(s"--- task #$tid done")
}
}
timer.schedule(timerTask, 0, 1000)
}
}
输出:
--- task #1 started
--- task #1 done
--- task #2 started
--- task #2 done
--- task #3 started
--- task #3 done
--- task #4 started
--- task #4 done
--- task #5 started
--- task #5 done
--- task #6 started
--- task #6 done
--- task #7 started
--- task #7 done
--- task #8 started
--- task #8 done
--- task #9 started
--- task #9 done
--- task #10 started
--- task #10 done
--- task #11 started
--- task #11 done
--- task #12 started
--- task #12 done
--- task #13 started
--- task #13 done
--- task #14 started
--- task #14 done
--- task #15 started
--- task #15 done
--- task #16 started
--- task #16 done
--- task #17 started
--- task #17 done
--- task #18 started
--- task #18 done
--- task #19 started
--- task #19 done
--- task #20 started
--- task #20 done
--- task #21 started
--- task #21 done
--- task #22 started
--- task #22 done
--- task #23 started
--- task #23 done
--- task #24 started
--- task #24 done
--- task #25 started
--- task #25 done
--- task #26 started
--- task #26 done
--- task #27 started
--- task #27 done
--- task #28 started
--- task #28 done
--- task #29 started
--- task #29 done
--- task #30 started
--- task #30 done
--- task #31 started
--- task #31 done
--- task #32 started
--- task #32 done
--- task #33 started
--- task #33 done
--- task #34 started
--- task #34 done
--- task #35 started
--- task #35 done
--- task #36 started
--- task #36 done
--- task #37 started
--- task #37 done
--- task #38 started