Search

Monday, June 22, 2015

How to pause Thread in Java using Sleep() and TimeUnit Example

There are multiple way to pause or stop execution of currently running thread, but putting 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 method just for pausing thread is not good. Those are tools for conditional wait and they doesn't upon time. A thread blocked using wait() will remain waiting until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of wait 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 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 acquiring and release a lock is not cheap. More importantly, why do you need to introduce lock just for pausing thread. Also one of the key difference between wait() and sleep() method is that, Thread.sleep() puts the current thread on wait but doesn't release any lock it is holding, but wait does release the lock it holds before going into blocking state. In short, multi-threading is not easy, even simple task like creating a thread, stopping a thread or pausing a thread require good knowledge of Java API. You need to use right method at right place. If you are serious about mastering multi-threading and concurrency, I would suggest to read Java Concurrency in Practice twice and do every example given on that book. That book will change how you look a problem from multi-threading perspective.
Read more »

No comments:

Post a Comment