Commit 42e2ce95 by Patryk Czarnik

Konto - pierwsza wersja bez synchronizacji

parent 72980bdd
package watki.konto;
public class BrakSrodkow extends Exception {
public BrakSrodkow() {
super();
}
public BrakSrodkow(String message) {
super(message);
}
}
package watki.konto;
public class Konto {
private final int numer;
private String wlasciciel;
private int saldo;
public Konto(int numer, String wlasciciel, int saldo) {
this.numer = numer;
this.wlasciciel = wlasciciel;
this.saldo = saldo;
}
public String getWlasciciel() {
return wlasciciel;
}
public void setWlasciciel(String wlasciciel) {
this.wlasciciel = wlasciciel;
}
public int getNumer() {
return numer;
}
public int getSaldo() {
return saldo;
}
@Override
public String toString() {
return "Konto nr " + numer + ", wł. " + wlasciciel + ", saldo: " + saldo;
}
public void wplata(int kwota) {
if(kwota <= 0) {
throw new IllegalArgumentException("Ujemna kwota w wplata");
}
saldo += kwota;
notify();
}
public void wyplata(int kwota) throws BrakSrodkow {
if(kwota <= 0) {
throw new IllegalArgumentException("Ujemna kwota w wyplata");
}
if(kwota > saldo) {
throw new BrakSrodkow("Brak środków na koncie nr " + numer
+". Żądano " + kwota + ", a jest " + saldo + ".");
}
saldo -= kwota;
}
}
package watki.konto;
public class Przeploty {
private static final int KWOTA = 10;
private static final int ILE_RAZY = 100_000;
public static void main(String[] args) {
Konto konto = new Konto(1, "Ala", 1_000_000);
System.out.println("Stan początkowy: " + konto.getSaldo());
Thread wplacacz = new Thread(() -> {
for(int i = 0; i < ILE_RAZY; i++) {
konto.wplata(KWOTA);
}
});
Thread wyplacacz = new Thread(() -> {
for(int i = 0; i < ILE_RAZY; i++) {
try {
konto.wyplata(KWOTA);
} catch (BrakSrodkow e) {
System.err.println(e);
}
}
});
wplacacz.start();
wyplacacz.start();
System.out.println("Wątki uruchomione, czekam na koniec");
try {
wplacacz.join();
wyplacacz.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Wątki zakończone.");
System.out.println("Stan końcowy: " + konto.getSaldo());
}
}
package watki.konto;
public class WyplacanieBezCzekania {
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.wyplata(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