简体   繁体   中英

Timer vs Thread primitive in Java

Has anyone observed that creating a thread that does work in a while(true) loop with a Thread.sleep(t) appears to consume more CPU than creating a Timer in Java with a wakeup of t? Anyone with JVM expertise know why this is? I've only really tried this on Windows and Linux x86.

According to the Javadoc for the Timer class , there's a background thread that does the work:

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.

How are you observing CPU usage? Have you tried a JVM profiler?

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