View Javadoc
1   package ch.hslu.exercises.sw05.input.ex2;
2   
3   import org.slf4j.Logger;
4   import org.slf4j.LoggerFactory;
5   
6   import java.util.List;
7   import java.util.stream.Collectors;
8   import java.util.stream.IntStream;
9   
10  public class DemoBankAccount {
11  
12      private static final int number = 1_000;
13      private static final int amount = 5_000_000;
14      private static final List<BankAccount> sourceBankAccounts = IntStream.range(0, number)
15              .mapToObj(x -> new BankAccount(amount))
16              .collect(Collectors.toList());
17      private static final List<BankAccount> targetBankAccounts = IntStream.range(0, number)
18              .mapToObj(x -> new BankAccount())
19              .collect(Collectors.toList());
20      private static final Logger LOG = LoggerFactory.getLogger(DemoBankAccount.class);
21  
22      public static void main(String[] args) {
23          final Thread[] threads = new Thread[number * 2];
24          for (int i = 0; i < number; i++) {
25              threads[i] = new Thread(new AccountTask(sourceBankAccounts.get(i), targetBankAccounts.get(i), amount));
26              threads[i + number] = new Thread(new AccountTask(targetBankAccounts.get(i), sourceBankAccounts.get(i), amount));
27          }
28          for (final Thread thread : threads) {
29              thread.start();
30          }
31          for (final Thread thread : threads) {
32              try {
33                  thread.join();
34              } catch (InterruptedException e) {
35                  return;
36              }
37          }
38  
39  
40          LOG.info("Bank accounts after transfers");
41          for (int i = 0; i < number; i++) {
42              LOG.info("source({}) = {}; target({}) = {};", i, sourceBankAccounts.get(i).getBalance(), i, targetBankAccounts.get(i).getBalance());
43          }
44      }
45  }