0

假设我有一个线程正在运行,里面有一个 timer.schedule(task, 5000)。现在让我们假设计时器开始运行,并且在线程的某个地方,有 thread.sleep()。当线程仍在休眠时,5000 毫秒过去了。定时器的任务在它所在的线程处于休眠状态时是否仍在运行?

谢谢

4

1 回答 1

4

Thread.sleep() cannot be somewhere in the thread, it can be in the task code, so the task execution will block for 5000 ms and then run to completion.

Note that java.util.Timer is a single-threaded scheduler, and if a task execution is blocked Timer will not be able to execute other scheduled tasks. See API

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.

于 2013-03-13T03:24:29.790 回答