TD 6 : Premiers objets
Classes et méthodes
Transformation de code
Main.java (avant)Toto.java (après)
class Main {
  public static void TotoBuild(Toto that,int aa,int bb) {
    that.a = aa;
    that.b = bb;
  }

  public static void TotoClear(Toto that) {
    that.a = 0;
    that.b = 0;
  }

  public static void TotoAdd(Toto that,int arg) {
    that.a += arg;
    that.b += arg;
  }

  // Pas d'argument 'that' ici....
  public static Toto TotoMakeUniform(int arg) {
    Toto res = new Toto();
    res.a = arg;
    res.b = arg;
    return res;

    // Ou alors

    Toto res = new Toto();
    TotoBuild(res,arg,arg);
    return res;
  }

  public static void main(String[] args) {
    Toto t = new Toto();
    TotoBuild(t,3,4);
    TotoAdd(t,5);
    TotoClear(t);
    Toto q = TotoMakeUniform(3);
  }
}
class Toto {
  public int a;
  public int b;

  // Vient de TotoBuild
  public Toto(int aa,int bb) {
    this.a = aa;
    this.b = bb;
  }

  // Vient de TotoClear
  public void Clear() {
    this.a = 0;
    this.b = 0;
  }
  
  // Vient de TotoAdd,
  // l'usage de "this." est facultatif en fait
  public void Add(int arg) {
    a += arg;
    b += arg;
  }

  // Vient de TotoMakeUniform,
  // 'static' signifie qu'il n'y a pas de this !
  // Pas vraiment de changement ici....
  public static Toto MakeUniform(int arg) {
    Toto res = new Toto();
    res.a = arg;
    res.b = arg;
    return res;

    // Ou alors
    
    return new Toto(arg,arg);
  }
}
Toto.java (avant)Main.java (après)
class Toto {
  public int a;
  public int b;
}
class Main {
  public static void main(String[] args) {
    Toto t = new Toto(3,4);
    t.Add(5);
    t.Clear();
    Toto q = Toto.MakeUniform(3); // Méthode statique !
  }
}
Retour aux réseaux de Petri
Appliquez la transormation de code aux fichiers Pool.java, Transition.java, Petri.java et Feux.java
Le dîner des philosophes
Définition du problème
Lors d'un banquet, n philosophes sont autour d'une table pour manger un plat de spagetti, situé au centre de la table. Les philosophes disposent d'une fourchette à leur gauche, et d'une fourchette à leur droite. La fourchette droite d'un philosophe est la fourchette gauche de son voisin de droite. Chaque philosophe réfléchit, mais décide de temps en temps de manger. Pour ce faire, il prend d'abord sa fourchette gauche, puis ensuite sa fourchette droite. Alors seulement, il prend une portion de pâtes du plat et la mange, puis il repose simultanément ses deux fourchettes.
Le problème est que ce dîner conduit à des dead locks, immaginez par exemples que tous les philosophes prennent leur fourchette gauche.... le plat risque de refroidir.
Programmation
Tracez, en faisant varier le nombre de philosophes, le temps moyen au bout duquel le système arrive à un dead-lock. Cela suppose d'avoir une fonction qui prend en argument le nombre de philosophe et construit le réseau de Petri correspondant.