import java.util.*;

/**
 * Una puerta para recibir mensajes.  Los receptores y emisores
 * se atienden en orden FIFO.
 */
public class Port
{
  SimplePort simplePort= new SimplePort();

  public synchronized Msg receive()
  {
    return simplePort.receive();
  }

  public synchronized Msg receive(long timeout)
  {
    return simplePort.receive(timeout);
  }
}

/**
 * Una puerta con varios receptores, pero que no necesariamente
 * se atienden en orden FIFO.
 */

class SimplePort
{
  Vector queue= new Vector();

  synchronized Msg receive()
  {
    if ( queue.isEmpty() )
      try { wait(); }
      catch ( InterruptedException I ) { throw new Error("Interrupcion"); }

    if ( queue.isEmpty() ) { throw new Error("Empty Queue!"); }
    Msg msg= (Msg)queue.elementAt(0);
    queue.removeElementAt(0);

    return (Msg)msg;
  }

  synchronized Msg receive(long timeout)
  {
    if ( queue.isEmpty() )
      try { wait(timeout); }
      catch ( InterruptedException I ) { throw new Error("Interrupcion"); }

    Msg msg= (Msg)queue.elementAt(0);
    queue.removeElementAt(0);

    return (Msg)msg;
  }

  synchronized void send(Msg msg)
  {
    queue.addElement(msg);
    notify();    
  }
}
