Created
March 17, 2022 09:36
-
-
Save bas-kirill/c65fd2cbb789330f69db9949b5fdd212 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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