Commit 6e0c3d39 by Patryk Czarnik

wait i notify

parent 0a400444
...@@ -54,4 +54,19 @@ public class Konto { ...@@ -54,4 +54,19 @@ public class Konto {
} }
saldo -= kwota; saldo -= kwota;
} }
public synchronized void wyplataCzekaj(int kwota) throws BrakSrodkow {
if(kwota <= 0) {
throw new IllegalArgumentException("Ujemna kwota w wyplata");
}
try {
while(kwota > saldo) {
wait();
}
saldo -= kwota;
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} }
package watki.konto;
public class WyplacanieZCzekaniem {
public static void main(String[] args) {
Konto konto = new Konto(1, "Ala", 2200);
System.out.println("Stan początkowy: " + konto.getSaldo());
Thread wplacacz = new Thread(() -> {
while(true) {
try {
Thread.sleep(2000);
konto.wplata(2000);
System.out.println("wpłaciłem, teraz jest " + konto.getSaldo());
} catch (InterruptedException e) {
}
}
});
Thread wyplacacz = new Thread(() -> {
while(true) {
try {
Thread.sleep(200);
System.out.println("próbuję wypłacić");
konto.wyplataCzekaj(300);
System.out.println("wypłaciłem, teraz jest " + konto.getSaldo());
} catch (BrakSrodkow e) {
System.err.println("BRAK KASY");
} catch (InterruptedException e) {
}
}
});
wplacacz.start();
wyplacacz.start();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment