Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it sensible to use Thread.Sleep()? [closed]

Tags:

I always see people using Thread.Sleep() for creating delays in processing or something similar and people are always derided for using it this way.

When is it sensible/required to use Thread.Sleep()?

like image 832
ediblecode Avatar asked Feb 23 '12 16:02

ediblecode


People also ask

Is it a good practice to use thread sleep?

No, using Thread. sleep() is not a good practice at all. Selenium provides two different methods to manage element synchronizations, the implicit and the explicitly wait.

What is wait concept why we will not use thread sleep method?

Sleep() method belongs to Thread class. Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context.

Should we use thread sleep in Java?

One of the way to achieve synchronization, implement wait is by calling Thread. sleep() function however, it is not recommended because this is not very stable and unreliable. The time has to be specified in milliseconds.

Does thread sleep block thread?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.


1 Answers

You should call Thread.sleep() when you actually need a delay in a background thread.

Do not call it to help synchronization (it won't), don't call it in a loop to wait for something (it'll be slow) and never call it on a UI thread (it'll freeze).

like image 143
SLaks Avatar answered Nov 07 '22 04:11

SLaks