added ex F

This commit is contained in:
Louis Heredero 2024-12-10 14:44:44 +01:00
parent e42def59f5
commit 700ae4a01a
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 53 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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);
}
}
}
}

View File

@ -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();
}
}