diff --git a/src/exercicses/ex_f/Account.java b/src/exercicses/ex_f/Account.java new file mode 100644 index 0000000..29377ba --- /dev/null +++ b/src/exercicses/ex_f/Account.java @@ -0,0 +1,17 @@ +package exercicses.ex_f; + +public class Account { + private int balance; + + public synchronized void withdraw(int amount) { + balance -= amount; + } + + public synchronized void deposit(int amount) { + balance += amount; + } + + public synchronized int getBalance() { + return balance; + } +} \ No newline at end of file diff --git a/src/exercicses/ex_f/Customer.java b/src/exercicses/ex_f/Customer.java new file mode 100644 index 0000000..fa82f6c --- /dev/null +++ b/src/exercicses/ex_f/Customer.java @@ -0,0 +1,26 @@ +package exercicses.ex_f; + +public class Customer implements Runnable { + private String name; + private Account account; + + public Customer(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); + } + } + } +} \ No newline at end of file diff --git a/src/exercicses/ex_f/TestingThreadInterferences.java b/src/exercicses/ex_f/TestingThreadInterferences.java new file mode 100644 index 0000000..d6edf05 --- /dev/null +++ b/src/exercicses/ex_f/TestingThreadInterferences.java @@ -0,0 +1,10 @@ +package exercicses.ex_f; + +public class TestingThreadInterferences { + public static void main(String[] args) { + // shared account object + Account account = new Account(); + (new Thread(new Customer("Damien", account))).start(); + (new Thread(new Customer("Hélène", account))).start(); + } +} \ No newline at end of file