Java - alternative to thread.sleep

强颜欢笑 提交于 2019-11-27 04:48:25

Try a ScheduledThreadPoolExecutor. It's supposed to give more reliable timing results.

Cratylus

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

Java is not a real-time system, you can not make a thread go away and come back on such a tight schedule. To schedule your program execution down to millisecond you need to use a different platform - like simpleRTJ or Java Real-Time extension.

The delay is likely to arbitrarily chosen, so I would question your need to real time interval timing.

If you need read time you need to busy wait for the time to reached. Giving up the CPU means you can't guarantee you will get it back exactly when you want.

You could implement wait/notify mechanism and delegate to another thread the responsibility of notify the other thread in wait state that the amount of time is passed and that it can go ahead ...

For example when the threadA need to wait for a certain amount of time you can put the thread in wait state and start a timer task that after a certain amount of time (interval ) call notify and wake up the ThreadA that go ahead, this could be an alternative .

If you want to be accurate with sounds you use a sequencer and set the tempo in BPM: sequencer.setTempoInBPM(120);

Android Freaks

The solution is to use a handler with a runnable and use of the method 'postDelayed'. Example:

new Handler().postDelayed(new Runnable() {
public void run () {
    // Do delayed stuff!
}
}, 5000L); //5 seconds delay 

https://stackoverflow.com/a/21680858

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!