ScheduledExecutorService 和使用 Thread.sleep() 滚动自己的 Runnable 之间的区别
使用 ScheduledExecutorService< 有什么好处/code>
的
scheduleAtFixedRate()
定期运行一段代码,而不是创建新的 Runnable
具有永远循环加上 Thread.sleep()
导致线程休眠所需的时间?
其中一种方法是否有性能提升?
What are the benefits of using ScheduledExecutorService
's scheduleAtFixedRate()
to run a piece of code on a regular basis instead of creating a new Runnable
that has a forever loop coupled with a Thread.sleep()
that causes the thread to sleep for the desired period?
Is there a performance gain with one of the methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用ScheduledExecutorService的最大好处是您不需要编写代码,并且它经过了良好的测试。它还支持开箱即用地取消任务,并且您可以安排多个任务。
另一个好处是其他开发人员知道
ScheduledExecutorService
的作用,他们可以阅读 javadoc,并且可以在公共论坛上提出有关它的问题并获得帮助,而获得自定义代码的帮助则更困难。ScheduledExecutorService 的 javadoc 也有这是一个很好的示例,说明如何创建一个任务,该任务每 10 秒执行一次,持续一个小时,然后被取消。
The biggest benefit of using
ScheduledExecutorService
is that you don't need to write the code, and that it is well tested. It does also have support for cancelling tasks out of the box, and you can schedule more than one task.Another benefit is that other developers know what the
ScheduledExecutorService
does, they can read the javadoc, and they can ask questions about it on puplic forums, and get help, while it's harder to get help for custom code.The javadoc for ScheduledExecutorService does also have a good example of how to create a tasks that executes every 10 seconds for an hour, and then gets cancelled.