package UE19_220425_Threads1.reallyParallel;

public class Main {
    public static void main(String[] args) {
        Konto a = new Konto();
        Konto b = new Konto();
        Konto c = new Konto();

        Runnable rAB = new Ueberweiser(a, b);
        Runnable rBC = new Ueberweiser(b, c);
        Runnable rCA = new Ueberweiser(c, a);
        Thread ab = new Thread(rAB);
        Thread bc = new Thread(rBC);
        Thread ca = new Thread(rCA);

        long start = System.currentTimeMillis();

        ab.start();
        bc.start();
        ca.start();

        try {
            ab.join();
            bc.join();
            ca.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(System.currentTimeMillis() - start + "ms");

        System.out.println("A: " + a.getKontostand());
        System.out.println("B: " + b.getKontostand());
        System.out.println("C: " + c.getKontostand());
    }
}
// 1883ms

class Konto {
    private int kontostand;

    public Konto() {
        this.kontostand = 0;
    }

    public int getKontostand() {
        return kontostand;
    }

    public void setKontostand(int kontostand) {
        this.kontostand = kontostand;
    }

    public synchronized void add(int betrag) {
        int wert = getKontostand();
        wert = wert + betrag;
        setKontostand(wert);
    }
}

class Ueberweiser implements Runnable {
    private static final int anzahl = 1000;
    private static final int betrag = 10;
    private final Konto von;
    private final Konto nach;

    public Ueberweiser(Konto von, Konto nach) {
        this.von = von;
        this.nach = nach;
    }

    public void run() {
        for (int i = 0; i < anzahl; i++) {
            von.add(-betrag);
            nach.add(betrag);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
