Methods wait()
and notify() belong to the class Object (java.lang.Object) and are methods that
are used to suspend and resume objects in execution. A call to the method
wait() will suspend the calling Thread. The Thread will be resumed when he will
receive a notification message. When called, the notify() method will send a
notification message to one of the suspended Threads. These methods can be used
to implement blocking semaphores.
Example:
Example of a blocking semaphore
implementation. The semaphore contains a variable indicating if this latter is
free or not. Methods take() and release() allow the acquisition
and the release of the semaphore.
When an object tries to take the
semaphore (by calling the take() method), if the semaphore is free, it will
become non free. Else, if non free, the calling object (Thread) will be blocked
by the call of the wait() method. When the semaphore will be released (by
calling release()), notify() will be called and the wait() method will
terminate. The semaphore will then be free and the object that was blocked will
be able to take it.
Examples:
Consider a
system having a file, several readers and several writers. Readers want to read
from the file while writers want to write to it. The restrictions are the
following:
A writer (W) can write to the file only if no other writer or reader is
currently accessing it.
A reader (R) can read from the file only if no other writer is currently
accessing it. Several readers can read at the same time.
Write a Java program including two Ws and four Rs, each of which
accesses the file every 0-50ms.