// Datei: LostUpdate.java
// Datum: 02.11.2018
// Autor: Brecht
// Thema: Zwei Threads greifen 100-mal miteinander konkurrierend
//        auf eine int-Variable mit dem Wert 1 zu und erhöhen
//        ihn jeweils um 1. Ausgabebeispiele:
//          Erhalte 34x2 und 66x3
//          Erhalte 25x2 und 75x3
//          Erhalte 29x2 und 71x3
//          Erhalte 35x2 und 65x3
// -------------------------------------------------------------
class Zaehler {
     int i = 0;                               // Der Zähler
  void update() { i++; }                      // Das Update
  int getValue() { return i; }
  void setValue(int wert) { this.i = wert; }  // Der Anfangswert
}
// -------------------------------------------------------------
class MyThread extends Thread {
  Zaehler myz;
  MyThread(Zaehler za) { this.myz = za; }
  public void run() {
    try { Thread.sleep(50); }
    catch(Exception e) {
      System.out.println("Sleep-Fehler");
      System.exit(0);
    }
    myz.update();
  }
}
// -------------------------------------------------------------
class LostUpdate {
  public static void main(String[] unused) throws Exception {
    int anz2 = 0;
    int anz3 = 0;
    Zaehler z = new Zaehler();
    for(int k=0; k<100; k++) {
      MyThread t1 = new MyThread(z);
      MyThread t2 = new MyThread(z);
      z.setValue(1);                   // Jeweiliger Anfangswert
      t1.start();
      t2.start();
      t1.join();
      t2.join();
      if(z.getValue() == 2) anz2++;
                       else anz3++;
    }
    System.out.println("Erhalte "+anz2+"x2 und "+anz3+" x3");
  }
}