LoslegenKostenlos loslegen

Parallele Threads für die Verarbeitung erstellen

Du entwickelst eine Anwendung zur Finanzanalyse, die eine große Anzahl an Transaktionen verarbeiten muss. Jede Transaktion erfordert CPU-intensive Berechnungen. Die Anwendung arbeitet derzeit sequenziell, ist aber zu langsam. Deine Aufgabe ist es, eine Multi-Threading-Lösung zu implementieren, um die Performance zu verbessern.

Die Klasse Transaction wurde für dich vorab geladen.

Diese Übung ist Teil des Kurses

Codeoptimierung in Java

Kurs anzeigen

Anleitung zur Übung

  • Erstelle Threads, die processTransaction() ausführen.
  • Starte alle Threads.
  • Warte, bis alle Threads abgeschlossen sind.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

public class TransactionProcessor {
    public static void main(String[] args) throws InterruptedException {
        List transactions = generateTransactions(1000);
        List threads = new ArrayList<>();
        for (int t = 0; t < 4; t++) {
            int start = t * 250;
            int end = (t == 3) ? transactions.size() : (t + 1) * 250;

            // Create thread that will run processTransaction()
            Thread thread = new ____(() -> {
                for (int i = start; i < end; i++) {
                    processTransaction(transactions.get(i));
                }
            });
            threads.add(thread);
            // Start the thread
            thread.____(); 
        }

        // Wait for all threads to complete
        for (Thread thread : threads) {
            thread.____();
        }
    }

    static void processTransaction(Transaction tx) {
        double result = 0;
        for (int i = 0; i < 1000; i++) {
            result += Math.sqrt(tx.amount * i);
        }
        tx.result = result;
    }

    static List generateTransactions(int n) {
        List list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(new Transaction(Math.random() * 1000));
        }
        return list;
    }
}
Code bearbeiten und ausführen