简体   繁体   中英

Java Thread.sleep() Cant Works Properly ,Why?

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);

            }

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!

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.

并不是说它没有用,只是您必须谨慎使用它,并且不要期望获得一致的结果,因为再次保证线程很少。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM