始める無料で始める

並列スレッドを作成して処理を実行する

あなたは、大量の取引を処理する必要がある金融分析アプリケーションを開発しています。各取引には 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;
    }
}
コードを編集して実行