开发者

What is the best way to count time spans?

If I would write a Clock application and I need to increase short seconds value literally after each second in time can I rely on Thread.sleep(1000)开发者_开发技巧 method?

Will it work fine if I would have millions of clocks running at the same time?


No, you cannot rely on Thread.sleep(1000), as it is up to the CPU scheduler as to when your thread is actually next run.

On top of that, CPU timings are not exactly accurate, so you will get natural deviation from true time unless you synchronize with a proper time service (atomic clock).

Having said that however, if you really are intending to run 'millions of clocks', you would be better served having a single timer that is being updated and merely storing the offset to that timer in each instance of the clock.

Also, by reducing the time the thread sleeps and updating the seconds only as appropriate, you can increase your accuracy. Note well though, as mentioned above, the sleep time is not guaranteed. This means even if you asked it to sleep for 10ms, it is technically possible for it not to return in 10 seconds (or, <<insert arbitrary time here>>


You generally want to update your seconds count at least a couple of times a second, otherwise it can be nearly an entire second out of sync with the real clock.

If at all possible, from there you want to have only one thread sleeping and updating the seconds value, and have a priority queue of events that need to be serviced. Each update, the clock looks at the event at the front of the priority queue, and if you've reached its time, processes it and checks the next one.


Look into the Java Concurrent API package. There are a number of new APIs that deal with multithreading and non-blocking algorithms.

For example, instead of having your program call Thread.sleep(1000), you can set up an [ScheduledExecutorService][1] and schedule a task to run every second. This will call your code and you use that to update your clock ticks. This move your code into a more producer/consumer model.

With Java 5, the need for such low-level access to thread (ie wait/notify) are alleviated. Take a look at some of the new stuff in the Java Concurrent package

[1]: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable, long, long, java.util.concurrent.TimeUnit)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜