View Javadoc
1   package ch.hslu.exercises.sw08.ex3;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   import java.util.List;
6   import java.util.concurrent.Callable;
7   import java.util.concurrent.ExecutorService;
8   import java.util.concurrent.Executors;
9   import java.util.concurrent.Future;
10  
11  import org.slf4j.LoggerFactory;
12  import org.slf4j.Logger;
13  
14  /**
15   * Demonstration der Bankgeschäfte - Aufgabe 2 - N1_EX_ThreadsSynch.
16   */
17  public final class DemoBankAccount {
18  
19      private static final Logger LOG = LoggerFactory.getLogger(DemoBankAccount.class);
20  
21      /**
22       * Privater Konstruktor.
23       */
24      private DemoBankAccount() {
25      }
26  
27  
28      /**
29       * Main-Demo.
30       *
31       * @param args not used.
32       * @throws InterruptedException wenn Warten unterbrochen wird.
33       */
34      public static void main(String[] args) throws InterruptedException {
35          final ArrayList<BankAccount> source = new ArrayList<>();
36          final ArrayList<BankAccount> target = new ArrayList<>();
37          final int amount = 200_000;
38          final int number = 10;
39          for (int i = 0; i < number; i++) {
40              source.add(new BankAccount(amount));
41              target.add(new BankAccount());
42          }
43          final List<Callable<Boolean>> tasks = new ArrayList<>();
44          for (int i = 0; i < number; i++) {
45              tasks.add(Executors.callable(new AccountTask(source.get(i), target.get(i), amount), true));
46              tasks.add(Executors.callable(new AccountTask(target.get(i), source.get(i), amount), true));
47          }
48          try (final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1)) {
49              long start = System.currentTimeMillis();
50              List<Future<Boolean>> futures = executor.invokeAll(tasks);
51              LOG.info("Duration: {} ms", System.currentTimeMillis() - start);
52  
53          }
54          LOG.info("Bank accounts after transfers");
55          for (int i = 0; i < number; i++) {
56              LOG.info("source({}) = {}; target({}) = {};", i, source.get(i).getBalance(), i, target.get(i).getBalance());
57          }
58      }
59  }