From 1e8e6eb1e9fc768f3e12f7285ee259c4f38d8c0a Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 10 Dec 2024 13:25:48 +0100 Subject: [PATCH] added ex E --- src/exercicses/ex_e/Account.java | 17 ++++++++++++ src/exercicses/ex_e/Customer.java | 26 +++++++++++++++++++ .../ex_e/TestingThreadInterferences.java | 10 +++++++ 3 files changed, 53 insertions(+) create mode 100644 src/exercicses/ex_e/Account.java create mode 100644 src/exercicses/ex_e/Customer.java create mode 100644 src/exercicses/ex_e/TestingThreadInterferences.java diff --git a/src/exercicses/ex_e/Account.java b/src/exercicses/ex_e/Account.java new file mode 100644 index 0000000..9824287 --- /dev/null +++ b/src/exercicses/ex_e/Account.java @@ -0,0 +1,17 @@ +package exercicses.ex_e; + +public class Account { + private int balance; + + public void withdraw(int amount) { + balance -= amount; + } + + public void deposit(int amount) { + balance += amount; + } + + public int getBalance() { + return balance; + } +} diff --git a/src/exercicses/ex_e/Customer.java b/src/exercicses/ex_e/Customer.java new file mode 100644 index 0000000..26f86a3 --- /dev/null +++ b/src/exercicses/ex_e/Customer.java @@ -0,0 +1,26 @@ +package exercicses.ex_e; + +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); + } + } + } +} diff --git a/src/exercicses/ex_e/TestingThreadInterferences.java b/src/exercicses/ex_e/TestingThreadInterferences.java new file mode 100644 index 0000000..5b74b38 --- /dev/null +++ b/src/exercicses/ex_e/TestingThreadInterferences.java @@ -0,0 +1,10 @@ +package exercicses.ex_e; + +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(); + } +}