DemoBankAccount.java

  1. package ch.hslu.exercises.sw05.input.ex2;

  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;

  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6. import java.util.stream.IntStream;

  7. public class DemoBankAccount {

  8.     private static final int number = 1_000;
  9.     private static final int amount = 5_000_000;
  10.     private static final List<BankAccount> sourceBankAccounts = IntStream.range(0, number)
  11.             .mapToObj(x -> new BankAccount(amount))
  12.             .collect(Collectors.toList());
  13.     private static final List<BankAccount> targetBankAccounts = IntStream.range(0, number)
  14.             .mapToObj(x -> new BankAccount())
  15.             .collect(Collectors.toList());
  16.     private static final Logger LOG = LoggerFactory.getLogger(DemoBankAccount.class);

  17.     public static void main(String[] args) {
  18.         final Thread[] threads = new Thread[number * 2];
  19.         for (int i = 0; i < number; i++) {
  20.             threads[i] = new Thread(new AccountTask(sourceBankAccounts.get(i), targetBankAccounts.get(i), amount));
  21.             threads[i + number] = new Thread(new AccountTask(targetBankAccounts.get(i), sourceBankAccounts.get(i), amount));
  22.         }
  23.         for (final Thread thread : threads) {
  24.             thread.start();
  25.         }
  26.         for (final Thread thread : threads) {
  27.             try {
  28.                 thread.join();
  29.             } catch (InterruptedException e) {
  30.                 return;
  31.             }
  32.         }


  33.         LOG.info("Bank accounts after transfers");
  34.         for (int i = 0; i < number; i++) {
  35.             LOG.info("source({}) = {}; target({}) = {};", i, sourceBankAccounts.get(i).getBalance(), i, targetBankAccounts.get(i).getBalance());
  36.         }
  37.     }
  38. }