시작하기무료로 시작하기

처리를 위한 병렬 스레드 생성

대량의 거래를 처리해야 하는 금융 분석 애플리케이션을 개발하고 있어요. 각 거래에는 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;
    }
}
코드 편집 및 실행