Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - alternative to thread.sleep

Tags:

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; } 
like image 382
user1189747 Avatar asked Feb 04 '12 19:02

user1189747


People also ask

What is the alternate for thread sleep?

Timer (More...) Monitor. Wait (More...) System.

Is it good practice to use thread sleep in Java?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

How do you stop a Java thread from going to sleep?

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.

What happens when thread's sleep () method is called?

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.


2 Answers

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

like image 128
Bill Avatar answered Oct 02 '22 13:10

Bill


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(); } 
like image 40
Cratylus Avatar answered Oct 02 '22 11:10

Cratylus