JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label core java interview Thread. Show all posts
Showing posts with label core java interview Thread. Show all posts

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

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

.