I tried this :
for(int i =0; i<10; i++)
{
long t1 = System.nanoTime();
try{Thread.sleep(1000);}catch(Exception e){}
double time = (System.nanoTime() - t1)/1000000;
System.out.println(i+") "+time);
}
And the output of this is :
0) 987.0
1) 999.0
2) 999.0
3) 999.0
4) 999.0
5) 1000.0
6) 999.0
7) 997.0
8) 999.0
9) 999.0
As it is apparent, Thread.sleep() is not exactly accurate, as it slept for 1000 ms only 1 time in 10 tries.
But I thought that it would take more time than 1000 ms, as it would need some time to calculate the value of t1 and time. Any specific reason why it sleeps for less time, and not more than what is specified? (My computer is certainly not a mega-super-computer, gifted by aliens, that it would calculate the value of t1 and time in negative time ! :P )
Also, how can I sleep a thread for exactly 1000 ms?