wait() and notify() in Java
Remember in article synch/Asynch Callback in Java I wrote, multithreading in Java is important and can improve performance. We can use callbacks to notify some threads finish executing. What if we don’t need to pass arguments, but we still want to implements multithreads falixable? Another simple way to let a thread wait and wake up is to use Object.wait() and Object.notify().
Keep in mind that:
- Object.wait() means suspend a thread.
- Object.notify() means wake a thread up.
Logic
To use wait() and notify(), we need to create an object to control execuations. This is similary to a lock. We use the common object to lock execuation steps.
Here is the sample code that keep waiting if the condition is not satisfied:
1 | synchronized (object) { |
Use the following code in other places to notify the above wait code:
1 | synchronized (object) { |
Keep in mind, there are two places need to be paid attention:
- use synchronized() to keep wait() and notify() under the same thread.
- use while loop instead of if loop to keep waiting and traking notifying.