Skip to content

Commit

Permalink
TheWellGroundedJavaDeveloper: FSOAccouunt, FSOMain(Concurrency)
Browse files Browse the repository at this point in the history
  • Loading branch information
currenjin committed Jan 20, 2025
1 parent 2d34f02 commit c23d088
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.currenjin.concurrency;

public class FSOAccount {
private double balance;

public FSOAccount(double openingBalance) {
this.balance = openingBalance;
}

public synchronized void deposit(int amount) {
balance += amount;
}

public double getBalance() {
return balance;
}

public synchronized boolean transferTo(FSOAccount other, int amount) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

if (amount >= balance) {
balance -= amount;
other.deposit(amount);
return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.currenjin.concurrency;

public class FSOMain {
private static final int MAX_TRANSFERS = 1_000;

public static void main(String[] args) throws InterruptedException {
FSOAccount a = new FSOAccount(10_000);
FSOAccount b = new FSOAccount(10_000);

Thread tA = new Thread(() -> {
for (int i = 0; i < MAX_TRANSFERS; i++) {
boolean ok = a.transferTo(b, 1);
if (!ok) {
System.out.println("Thread A failed at " + i);
}
}
});

Thread tB = new Thread(() -> {
for (int i = 0; i < MAX_TRANSFERS; i++) {
boolean ok = b.transferTo(a, 1);
if (!ok) {
System.out.println("Thread B failed at " + i);
}
}
});

tA.start();
tB.start();
tA.join();
tB.join();

System.out.println("End: " + a.getBalance() + " : " + b.getBalance());
}
}

0 comments on commit c23d088

Please sign in to comment.