简体   繁体   中英

Is Java's Timer task guaranteed not to run concurrently?

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

task保证在任何给定时间由单个线程运行吗?

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.

每个Timer有一个单独的线程,所以你的问题的答案是肯定的

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM