Inter thread Communication:
The preceding instance unconditionally blocked other threads from asynchronous access to following methods. This use of the implicit monitors in Java objects is powerful; other than you can achieve a more subtle level of control by inter procedure communication. As you will look this is especially simple in Java.
As discuses earlier, multithreading exchange event loop programming through separating your tasks into discrete and logical units. A Thread also gives secondary advantages. They do away along with polling. Polling is commonly implemented through a loop which is used to check a few conditions repeatedly. At one the condition is true, around action is taken. This wastes CPU time. For instance, let consider the classic queuing problem,. Where one thread is producing a few data and another is consuming it. For make the problem more interesting, assume that the producer has to wait until the consumer is finished before it produces more data. Within a polling system, a consumer would waste several CPU cycles although it waited for the producer to produce. At once the producer was finished; it would begin polling wasting more CPU cycles waiting for the consumer to finish, and many more. Clearly this condition is undesirable.
To prevent poling, Java involves an elegant inter process communication mechanism through the wait( ), notify( ) and notify All( ) functions. Those methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from inside a synchronized method. While conceptually advanced from a computer science perspective, the rules for using these methods are in fact quite easy:
- wait( ) tells the calling thread to produce up the monitor and go to sleep until a few other thread enters the similar monitor and calls notify( )
- notify( ) wakes up the first thread which called wait( ) on the similar object
- notifyAll( ) wakes up all the threads which called wait( ) on the similar object. A highest priority thread will run first