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 scenario. Millisecond accuracy is important in my program.
Here is the algorithm where I don't want to go back to check for condition until expectedElapsedTime
has passed by.
while (condition) { time = System.currentTimeMillis(); //do something if (elapsedTime(time) < expectedElapsedTime) ) { pause the loop // NEED SUBSTITUTE FOR Thread.sleep() } // Alternative that I have tried but not giving good results is while ((elapsedTime(time) < expectedElapsedTime)) { //do nothing } } long elapsedTime(long time) { long diff = System.currentTimeMillis() - time; return diff; }
Timer (More...) Monitor. Wait (More...) System.
Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.
Answer: We stop Java thread from sleeping using the interrupt() method. Any thread that is waiting or sleeping can be interrupted by invoking the interrupt() method of the Thread class.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
Try a ScheduledThreadPoolExecutor. It's supposed to give more reliable timing results.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With