/
Nicholas
/
java_basics
Обзор
Документация
Войти
/
Nicholas
/
java_basics
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Multithreading/Transactions/src/Bank.java
57 строк
2 KB
Nicholay Sokolovsky
19.2 FIX
24 ноя 2023, 10:50
24 ноя 2023, 10:50
e7b22fa
Код
Авторство
О чём код?
import java.util.HashMap; import java.util.Random; public class Bank { final static String ACCHEADER = "4070281000000"; private HashMap<String, Account> accounts = new HashMap<>(); private final Random random = new Random(); private long accNumber = 1; public synchronized boolean isFraud(String fromAccountNum, String toAccountNum, long amount) throws InterruptedException { if (amount > 50000) { Thread.sleep(1000); boolean fraud = random.nextBoolean(); if (fraud) { accounts.get(fromAccountNum).setBlock(); accounts.get(toAccountNum).setBlock(); } return fraud; } else return false; } public void transfer(String fromAccountNum, String toAccountNum, long amount) throws InterruptedException { if (!accounts.get(fromAccountNum).getBlock() && !accounts.get(toAccountNum).getBlock() && !fromAccountNum.equals(toAccountNum) && !isFraud(fromAccountNum, toAccountNum, amount)) { accounts.get(fromAccountNum).setMoney(accounts.get(fromAccountNum).getMoney() - amount); accounts.get(toAccountNum).setMoney(accounts.get(toAccountNum).getMoney() + amount); } } public boolean getBlockAcc(String acc) { return accounts.get(acc).getBlock(); } public long getBalance(String accountNum) { return accounts.get(accountNum).getMoney(); } public long getSumAllAccounts() { long balance = 0; for (Account acc : accounts.values()) { balance = balance + acc.getMoney(); } return balance; } public String openAccount(long amount) { String accountNum = ACCHEADER + String.format("%07d", accNumber++); accounts.put(accountNum, new Account(amount, accountNum)); return accountNum; } public int numOfAccounts() { return accounts.size(); } }