Previous | Home | Next |
Intertthread communication is similar as interprocess communication, which allow other thread to execute if one is waiting for resource. Such as in Producer Consumer problem if producer is producing some value then consumer have to wait. This Polling system may waste many CPU cycle. Thus interprocess communication help to reduce wasting of CPU cycles.
In Java innerthread communication machanism can be achieved by help of three methods.
-
wait(): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
-
notify(): This method wakes up the first thread that called wait( ) on the same object.
-
notifyAll(): This method wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first. But if there are no waiting threads, the notifys are forgotten.
The complete syntex of all three methods are.
final void wait() throws InterruptedException;
It have two overloades
- final voidwait(long timeout)
- final voidwait(long timeout, in nansec)
Here timeout in milli sec and nansec measured in nanosecond.
final void notify();
final void notifyAll();
An Example of innerthread communication is Producer consumer problem
/* * imlementing interthread communication */ package interthreadcommunicationex; class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } } public class interthrdcommn { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }
Output:
run: Put: 0 Got: 0 Put: 1 Got: 1 Put: 2 Got: 2 Put: 3 Got: 3 Put: 4 Got: 4 Put: 5 Got: 5 Put: 6 Got: 6 Put: 7 Got: 7 Put: 8 Got: 8
Previous | Home | Next |