added ex G
This commit is contained in:
parent
700ae4a01a
commit
6111228c02
23
src/exercicses/ex_g/Account.java
Normal file
23
src/exercicses/ex_g/Account.java
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
package exercicses.ex_g;
|
||||||
|
|
||||||
|
public class Account {
|
||||||
|
private int balance;
|
||||||
|
|
||||||
|
public void withdraw(int amount) {
|
||||||
|
synchronized (this) {
|
||||||
|
balance -= amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deposit(int amount) {
|
||||||
|
synchronized (this) {
|
||||||
|
balance += amount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getBalance() {
|
||||||
|
synchronized (this) {
|
||||||
|
return balance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
26
src/exercicses/ex_g/BankEmployee.java
Normal file
26
src/exercicses/ex_g/BankEmployee.java
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
package exercicses.ex_g;
|
||||||
|
|
||||||
|
public class BankEmployee implements Runnable {
|
||||||
|
private String name;
|
||||||
|
private Account account;
|
||||||
|
|
||||||
|
public BankEmployee(String name, Account account) {
|
||||||
|
this.name = name;
|
||||||
|
this.account = account;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
while (true) {
|
||||||
|
account.deposit((int) (Math.random() * 1000));
|
||||||
|
System.out.println(name + " has deposited money on account with new balance " + account.getBalance());
|
||||||
|
account.withdraw((int) (Math.random() * 1000));
|
||||||
|
System.out.println(name + " has withdrawn money from the account with new balance " + account.getBalance());
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
10
src/exercicses/ex_g/TestingSynchronizedStatements.java
Normal file
10
src/exercicses/ex_g/TestingSynchronizedStatements.java
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package exercicses.ex_g;
|
||||||
|
|
||||||
|
public class TestingSynchronizedStatements {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// shared account object
|
||||||
|
Account account = new Account();
|
||||||
|
(new Thread(new BankEmployee("Mrs Fournier", account))).start();
|
||||||
|
(new Thread(new BankEmployee("Mr Schmidhalter", account))).start();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user