Reputation: 40416
Below my code Gives me strange Results, Obviously you must be getting 1000
, but in reality do not expect anything below 3500. I got 3500-4500 on different runs. And I read some where that Thread.sleep is completely unreliable. Why does java not Depcrecate it, if its useless?
Is There Any solution For that?
class MyClass {
public static void main ( String[] args ) {
long start, end, took;
start = System.currentTimeMillis();
for ( int i=0; i<200; i++) {
try {
Thread.sleep (5);
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
end = System.currentTimeMillis();
System.out.println("Start :: " + start);
System.out.println("end :: " + end);
took = end -start;
System.out.println ("Took: " + took);
}
Upvotes: 0
Views: 797
Reputation: 6131
If you need some kind of Timer a low level Thread is not the right thing. A Thread make use of the underlaying OS Scheduler to distribute CPU Time to the Processes of the System. Infact the JavaVM also spawns Processes and a Thread is fed with CPU Time by a JavaVM Scheduler.
When you switch a thread into the state of sleeping you have to wait until the Scheduler wake you up again.
If you need accurate Timing take a look at TimerTask and Timer
Upvotes: 0
Reputation: 47954
It does exactly what it says, which is sleep for at least 5 milliseconds. Nothing guarantees it won't wait longer, it never claims to. (admittedly the javadoc on the method can give the impression that the thread will promptly resume, in reality this is up to operating system/jvm and you have no control over it.)
It is certainly strange that it takes 3-4 seconds to run. Depends on your platform/operating system and what else your computer may be doing at the time. I get results between 1010 and 1020 running that exact code snippet. Is that what you're actually running or did you extract that as an example from a larger program?
Older versions of windows have around a minimum 15ms sleep by default, which would explain values over 3 seconds. Some JVMs tinker with windows to get better sleep resolution, but for any specific combination of JVM version and OS version, tough to say!
Upvotes: 4
Reputation: 785068
Precise timing in Thread.sleep
is not guaranteed and that's precisely the reason you're getting different timings on different runs.
Better to use RealTimeThread for real time calculation in Java.
Upvotes: 1
Reputation: 18488
It is not that it is useless, it is just that you have to use it with caution, and not expecting consistent results, since again with threads very little is guaranteed.
Upvotes: 0