DemoBankAccount.java

package ch.hslu.exercises.sw08.ex3;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * Demonstration der Bankgeschäfte - Aufgabe 2 - N1_EX_ThreadsSynch.
 */
public final class DemoBankAccount {

    private static final Logger LOG = LoggerFactory.getLogger(DemoBankAccount.class);

    /**
     * Privater Konstruktor.
     */
    private DemoBankAccount() {
    }


    /**
     * Main-Demo.
     *
     * @param args not used.
     * @throws InterruptedException wenn Warten unterbrochen wird.
     */
    public static void main(String[] args) throws InterruptedException {
        final ArrayList<BankAccount> source = new ArrayList<>();
        final ArrayList<BankAccount> target = new ArrayList<>();
        final int amount = 200_000;
        final int number = 10;
        for (int i = 0; i < number; i++) {
            source.add(new BankAccount(amount));
            target.add(new BankAccount());
        }
        final List<Callable<Boolean>> tasks = new ArrayList<>();
        for (int i = 0; i < number; i++) {
            tasks.add(Executors.callable(new AccountTask(source.get(i), target.get(i), amount), true));
            tasks.add(Executors.callable(new AccountTask(target.get(i), source.get(i), amount), true));
        }
        try (final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1)) {
            long start = System.currentTimeMillis();
            List<Future<Boolean>> futures = executor.invokeAll(tasks);
            LOG.info("Duration: {} ms", System.currentTimeMillis() - start);

        }
        LOG.info("Bank accounts after transfers");
        for (int i = 0; i < number; i++) {
            LOG.info("source({}) = {}; target({}) = {};", i, source.get(i).getBalance(), i, target.get(i).getBalance());
        }
    }
}