Let’s see an example implementing
these methods:
class Shared {
int num=0; boolean value = false; synchronized int get() { if (value==false) try { wait(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("consume: " + num); value=false; notify(); return num; } synchronized void put(int num) { if (value==true) try { wait(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } this.num=num; System.out.println("Produce: " + num); value=false; notify(); } } class Producer extends Thread { Shared s; Producer(Shared s) { this.s=s; this.start(); } public void run() { int i=0; s.put(++i); } } class Consumer extends Thread{ Shared s; Consumer(Shared s) { this.s=s; this.start(); } public void run() { s.get(); } } public class InterThread{ public static void main(String[] args) { Shared s=new Shared(); new Producer(s); new Consumer(s); } } |
Output of the Program:
C:\nisha>javac InterThread.java
C:\nisha>java InterThread Produce: 1 consume: 1 |
In this program, two threads "Producer"
and "Consumer" share the synchronized methods of the class "Shared".
At time of program execution, the "put( )" method is invoked
through the "Producer" class which increments the variable "num"
by 1. After producing 1 by the producer, the method "get(
)" is invoked by through the "Consumer" class which
retrieves the produced number and returns it to the output. Thus the Consumer
can't retrieve the number without producing of it.