public class ProductorConsumidor {
    
    public ProductorConsumidor() {
      Almacen almacen = new Almacen();
      Productor p = new Productor(almacen, 1);
      Consumidor c = new Consumidor(almacen, 1);
      p.start(); 
      c.start();        
    }
    
    public static void main(String[] args) {
        new ProductorConsumidor();
    }

    class Almacen {
       private int contenidos;
       private boolean disponible = false;
       
       public synchronized int get() {
          while (disponible == false) {
             try {
                wait();
             }
             catch (InterruptedException e) {
             }
          }
          disponible = false;
          notifyAll();
          return contenidos;
       }  
       
       public synchronized void put(int value) {
          while (disponible == true) {
             try {
                wait();
             }
             catch (InterruptedException e) { 
             } 
          }
          contenidos = value;
          disponible = true;
          notifyAll();
       }
    }

    class Consumidor extends Thread {
       private Almacen almacen;
       private int numero;
       public Consumidor(Almacen c, int unNnumero) {
          almacen = c;
          this.numero = unNnumero;
       }
       
       @Override
       public void run() {
          int value = 0;
             for (int i = 0; i < 10; i++) {
                value = almacen.get();
                System.out.println("Consumidor #" 
                            + this.numero
                            + " toma: " + value);
             }
       }
    }

    class Productor extends Thread {
        private Almacen almacen;
        private int numero;

        public Productor(Almacen c, int unNumero) {
            almacen = c;
            this.numero = unNumero;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                almacen.put(i);
                System.out.println("Productor #" + this.numero
                + " pone: " + i);
                try {
                sleep((int)(Math.random() * 100));
                } catch (InterruptedException e) { }
            }
        }
    }
}
