Distinction between ScheduledExecutorService and rolling your own Runnable with Thread.sleep()

匆匆过客 提交于 2019-12-21 20:45:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6183749/distinction-between-scheduledexecutorservice-and-rolling-your-own-runnable-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!