Skip to content

Instantly share code, notes, and snippets.

@bas-kirill
Created March 17, 2022 09:36
Show Gist options
  • Save bas-kirill/c65fd2cbb789330f69db9949b5fdd212 to your computer and use it in GitHub Desktop.
Save bas-kirill/c65fd2cbb789330f69db9949b5fdd212 to your computer and use it in GitHub Desktop.
package ru.tfs.concurrency.task2;
import java.util.concurrent.Exchanger;
import java.util.concurrent.locks.ReentrantLock;
public class AccountThread implements Runnable {
// private static final ReentrantLock lock = new ReentrantLock(true);
private static final Object lock = new Object();
private final Account accountFrom;
private final Account accountTo;
private final int money;
public AccountThread(Account accountFrom, Account accountTo, int money) {
this.accountFrom = accountFrom;
this.accountTo = accountTo;
this.money = money;
}
@Override
public void run() {
for (int i = 0; i < 4000; i++) {
synchronized (lock) {
boolean goodTransaction = accountFrom.takeOffMoney(money);
System.out.println("Transaction status: " + goodTransaction);
if (!goodTransaction) {
throw new RuntimeException("Account from balance became negative");
}
accountTo.addMoney(money);
System.out.println("Cash balance of the first account: " + accountFrom.getCacheBalance());
System.out.println("Cash balance of the second account: " + accountTo.getCacheBalance());
System.out.println("-----");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment