How to pause Thread in Java using Sleep() and TimeUnit in java Example
GIAN Tutorials
1:19 AM
There are many ways to pause or stop the execution of currently running thread, but putting the thread into sleep state using Thread.sleep() method is the right way to introduce pause. Some people would say, why not use wait and notify ?. Using those methods just for pausing thread is not good. Those are the tools for a conditional wait and they don't depend on upon time. A thread blocked using wait() will remain to wait until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of wait() method is different, they are designed for inter-thread communication in Java . By using sleep() method, you pause the current for some given time. You should never use sleep() in place of wait() and notify() and vice-versa. There is another reason why to wait and notify should not be used to pause the thread, they need lock. You can only call them from a synchronized method or block and acquire and release a lock is not cheap. How to pau