简体   繁体   English

Java中的计时器与线程原语

[英]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? 有没有人观察到创建一个在Thread.sleep(t)的while(true)循环中运行的线程似乎比在Java中创建t的唤醒定时器消耗更多的CPU? Anyone with JVM expertise know why this is? 有JVM专业知识的人都知道为什么会这样吗? I've only really tried this on Windows and Linux x86. 我只在Windows和Linux x86上真正尝试过。

According to the Javadoc for the Timer class , there's a background thread that does the work: 根据Timerdoc类Javadoc ,有一个后台线程可以完成工作:

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. 与每个Timer对象相对应的是一个单独的后台线程,该线程用于依次执行所有Timer的任务。 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? 您如何观察CPU使用率? Have you tried a JVM profiler? 您是否尝试过JVM Profiler?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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