Java - alternative to thread.sleep

前端 未结 8 629
礼貌的吻别
礼貌的吻别 2020-11-30 10:00

I have a requirement to pause a while loop for a specific number of milliseconds. I have tried using Thread.sleep(duration) but it is not accurate, especially in a looping s

相关标签:
8条回答
  • 2020-11-30 10:35

    Don't forget about garbage collector pauses. It can beat all your plans

    0 讨论(0)
  • 2020-11-30 10:36

    What do you expect?

    If you go to sleep then once your process is again runable it will have to wait for the thread scheduler to schedule it again.

    I mean if you go to sleep for 50 seconds that does not mean that your process will be running in exactly 50 seconds.Because ater it wakes and is runnable it will have to wait to be scheduled to CPU which takes extra time plus the time you have for context switch.

    There is nothing you can do to control it so you can not have the accuracy you are saying.

    For your case I would suggest a spinning loop instead.

    long now = System.currentTimeMillis();   
    while(now < expectedElapsedTime){
        now = System.currentTimeMillis();
    }
    
    0 讨论(0)
提交回复
热议问题