ScheduledExecutorService与使用Thread.sleep()滚动自己的Runnable之间的区别 [英] Distinction between ScheduledExecutorService and rolling your own Runnable with Thread.sleep()

查看:221
本文介绍了ScheduledExecutorService与使用Thread.sleep()滚动自己的Runnable之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 <$有什么好处? c $ c> ScheduledExecutorService 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?

推荐答案

使用<$ c $的最大好处c> ScheduledExecutorService 是您不需要编写代码,并且它经过了充分测试。它还支持取消开箱即用的任务,您可以安排多个任务。

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.

另一个好处是其他开发人员知道 ScheduledExecutorService 的作用,他们可以读取javadoc,他们可以询问关于它在puplic论坛上的问题,并获得帮助,虽然很难获得自定义代码的帮助。

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.

ScheduledExecutorService 也有一个很好的例子,说明如何创建每10秒执行一次的任务一个小时,然后取消。

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.

这篇关于ScheduledExecutorService与使用Thread.sleep()滚动自己的Runnable之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆