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);
}
Precise timing in
Thread.sleepis 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.