
/**********************************************************************/
/*                                                                    */ 
/*                        TD 1, Exercice 1                            */
/*                  Solution utilisant les wait/notify                */
/*                                                                    */
/**********************************************************************/


public class UnEntier {
    private int val;
    
    public UnEntier (int x) {
	val = x;
    }
    
    synchronized public int intValue() {
	return val;
    }
    
    synchronized public void setValue(int x) { 
        System.out.print("\nx: "+val+" -> "+x);
        val = x; 
        notifyAll();
    }
}


public class Proc1 extends Thread {

    UnEntier refI;
    
    Proc1(UnEntier ent) {
        refI = ent; 
        setName("Proc1");
    }

    public void setRef() {
	 refI.setValue(42);
    }
            
    public void run() {
        System.out.print("\nP1 starts...");
        try {
	    sleep(100);
	} catch (InterruptedException e) { return ; }
        setRef();
        System.out.print("\nP1 ends...");            
     }
}


public class Proc2 extends Thread {

    UnEntier refI;

    Proc2(UnEntier ent) {
        refI = ent;
        setName("Proc2");
    }

    synchronized public void waitForRef() {
	try {
	      synchronized(refI) {
                  while(refI.intValue()!=42) {
                      System.out.print("\nP2 waits...") ; 
                      refI.wait(); 
                  }; 
              };
            } catch (InterruptedException e) { return ; }            
	return;
    }
 
    public void run() {
        System.out.print("\nP2 starts...");            
        waitForRef();
        System.out.print("\nP2 ends...");            
    }
}

        
public class Exo1Bis {

    public static void main(String[] args) {
        UnEntier i = new UnEntier(0);
        Proc1 p1 = new Proc1(i);
        Proc2 p2 = new Proc2(i);
        
	p1.start() ;
	p2.start() ;
    }
}
    
                        
        
        

    
