Is Java's Timer task guaranteed not to run con

2019-03-30 15:20发布

new Timer(...).schedule(task)

Is task guaranteed to be run by a single thread at any given time?

3条回答
The star\"
2楼-- · 2019-03-30 16:09

Indeed. They all run on a same background thread corresponded to the Timer object in sequence. BUT two different Timer instances will run (I believe) on different threads, so you have to save reference to a timer object to schedule more tasks sequentialy.

查看更多
女痞
3楼-- · 2019-03-30 16:19

There is a single thread per Timer, so the answer to your question is yes

查看更多
欢心
4楼-- · 2019-03-30 16:21

From the Javadoc

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.

So, yes, you get a new Thread (separate from the caller's thread). Every task in that timer shares the same thread.

查看更多
登录 后发表回答