始める無料で始める

処理のための並列スレッドの作成

大量のトランザクションを処理する必要がある財務分析アプリケーションを開発しています。各トランザクションでは CPU 負荷の高い計算が必要です。現在は逐次処理を行っていますが、処理が遅すぎます。そこで、パフォーマンスを改善するためにマルチスレッドの実装を任されています。

Transaction クラスはあらかじめ読み込まれています。

この演習はコースの一部です

Javaコード最適化

コースを見る

演習の手順

  • processTransaction() を実行する Thread を作成します。
  • すべてのスレッドを開始します。
  • すべてのスレッドの完了を待ちます。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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;
    }
}
コードを編集して実行