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
2
3
4
5
6
7
8
synchronized (object) {
while (!condition) {
object.wait();
}
// do something:
// those things will wait
// until other place calls notify
}

Use the following code in other places to notify the above wait code:

1
2
3
synchronized (object) {
object.notify();
}

Keep in mind, there are two places need to be paid attention:

  1. use synchronized() to keep wait() and notify() under the same thread.
  2. use while loop instead of if loop to keep waiting and traking notifying.