package towersofhanoi;
/**
 * Creates a new instance of ExecParallel
 */
public class ExecParallel extends ExecutionModel {
  ExecParallel() {
    super();
  }
  ExecParallel(int nrDisks) {
    super(nrDisks);
  }
  void hanoi(boolean flgDisplay, int n, int src, int dst, int aux) {
    if( n==1 ) {
      if( flgDisplay )
        System.out.println("    moving disk " + n + ": " + "pino-" + src + " ---> " + "pino-" +dst);
    } else {
      // move n-1 discos de src para aux deixando disco de numero #n em src
      ExecParallel.ThreadA thA = (new ExecParallel()).new ThreadA(flgDisplay, n, src, dst, aux);
      thA.start();
      try {
        thA.join();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
      
      // move disco #n de src para dst
      if( flgDisplay )
        System.out.println("    moving disk " + n + ": " + "pino-" + src + " ---> " + "pino-" +dst);
      
      // move n-1 discos de Aux para Dst sobre disco #n
      ExecParallel.ThreadB thB = (new ExecParallel()).new ThreadB(flgDisplay, n, src, dst, aux);
      thB.start();
      try {
        thB.join();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }
  }
  class ThreadA extends Thread {
    boolean  flgDisplay;
    int n;
    int src;
    int dst;
    int aux;
    ThreadA(boolean flgDisplay, int n, int src, int dst, int aux) {
      this.flgDisplay = flgDisplay;
      this.n   = n;
      this.src = src;
      this.dst = dst;
      this.aux = aux;
    }
    public void run(){
      // move n-1 discos de src para aux deixando disco de numero #n em src
      hanoi(flgDisplay, n-1, src, aux, dst);
    }
  }
  class ThreadB extends Thread {
    boolean  flgDisplay;
    int n;
    int src;
    int dst;
    int aux;
    ThreadB(boolean flgDisplay, int n, int src, int dst, int aux) {
      this.flgDisplay = flgDisplay;
      this.n = n;
      this.src = src;
      this.dst = dst;
      this.aux = aux;
    }
    public void run(){
      // move n-1 discos de Aux para Dst sobre disco #n
      hanoi(flgDisplay, n-1, aux, dst, src);
    }
  }
}

