Producer Consumer Sample using wait( ) & notify( )  Peter Komisar


// Class Musket has just two members, the load and fire methods.

class Musket{

// the synchronized load method
 synchronized boolean load(boolean loaded){
  while(loaded == true){
    try{
        wait( );                     // wait( ) method from the Object class
        }
    catch(InterruptedException e){ }
  }
 
  loaded=true;
  System.out.println(Thread.currentThread().getName() + ": loaded ");
       notify( );                   // notify( ) method from the Object class
  return loaded;
  }

// the synchronized fire  method
synchronized boolean fire(boolean loaded){
 
  while(loaded == false){
  try{
     wait( );                       // wait( ) method from the Object class
     }
     catch( InterruptedException e){ }
  }

  loaded=true;
  System.out.println(Thread.currentThread().getName() +": fired ");
  loaded=false;
  notify( );                       // notify( ) method from the Object class
  return loaded;
  }
}

/* The Gunners extends Thread and provides the neccessary run method( ). It also creates three instances
    of itself. These new threads will be invoking the run( ) method once they are started. In the run method an
    instance of the Musket class is created  to provide the synchronized load and fire methods. When  methods
    are declared synchronized they are implicitly synchronized on this, the containing class instance.
*/

class Gunners extends Thread {
Gunners(String s){
super(s);
}
  static int i=0;
  boolean loaded = false;
  public static void main(String args[]){
 
     Gunners g1=new Gunners("A. Left" );
     Gunners g2=new Gunners("B.                             Right" );
     Gunners g3=new Gunners("C.              Center");
 
    g1.start();
    g2.start();
    g3.start();
    }
 
   public void run( ){
 
    for(int i=0; i<3;i++){
        Musket m=new Musket( );
        boolean b =false;
        b=m.load(b);
        b=m.fire(b);
        try{Thread.currentThread().sleep             // delays of war
        (100);}catch(InterruptedException ie){ }
      }
   }
}