Consider the classic queueing problem, where one thread is producing some data and the other is consuming it. To make the problem more interesting, assume that the producer has to wait until it will generate more data before the consumption is finished.
In a polling system, consumers waste a lot of CPU cycles, and it waits for producers to produce. Once the production is over, start polling, wasting more CPU cycles waiting for the consumer?? Complete, and so on. Obviously, this situation is not desirable.
To avoid polling, Java includes an elegant inter-process communication mechanism through the following methods:
Wait (): This method tells the calling thread to discard the monitor and go to sleep until another thread enters the same monitor and calls notify ().
notify (): This method wakes the first thread to call Wait () on the same object.
notifyall (): This method wakes all threads on the same object that call Wait (). The highest-priority thread will run first.
These methods are implemented as final methods in object, so all classes have them. These three methods can only be called from within a synchronized context.
These methods are declared in the object. Various forms of wait () exist so that you can specify a period of time to wait.
Example:
The following sample program includes four classes: Q, want to synchronize the queue, Producer, that is, the production queue of the entry thread object; Consumer, which consumes the queue's entry thread object and the Pc,tiny class, creates a Q, producer, and consumer.
The correct way to write this program in Java is to use the wait () and notify () methods to signal in two directions as follows:
Put: 1Got: 1Put: 2Got: 2Put: 3Got: 3Put: 4Got: 4Put: 5Got: 5
Java Inter-thread communication