2. (Thread)배열로 1억 데이터를 10개 쓰레드로 돌리면?

이월(0216tw)·2024년 5월 13일
  • 이 포스트는 자바의 스레드를 시나리오 형식으로 공부한 코드 내용입니다.

시나리오2

대용량의 0~1억까지의 수를 배열에 입력하고 싶습니다.
처음에는 하나의 쓰레드로 진행하고 두번째는 10개의 쓰레드로 나누어 진행해주세요.
각 케이스에 대한 걸린 시간을 마지막에 출력해주세요.

package ThreadExample;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;


public class ThreadScenario02 {

    static int[] arrCheck;

    @BeforeEach
    public void setUp() { //비교용 데이터 셋
        arrCheck = new int[100000001];
        for(int i = 0 ; i<arrCheck.length; i++) {
            arrCheck[i] = i;
        }
    }

    @Test
    @DisplayName("단일 쓰레드로 1억 데이터 넣어보기")
    public void 단일쓰레드_1억_데이터_입력() {

        int arr[] = new int[100000001];
        long startTime = System.currentTimeMillis();

        for(int i = 0 ; i<arr.length; i++) {
            arr[i] = i;
        }
        long executionTime = System.currentTimeMillis() - startTime;

        // 실행 시간 출력
        System.out.println("단일 스레드 실행 시간 : " + executionTime + " milliseconds");

        Assertions.assertArrayEquals(arrCheck , arr);

    }


    @Test
    @DisplayName("멀티쓰레드(10개)로 1억 데이터 넣어보기")
    public void 멀티쓰레드_10개로_1억데이터_입력() {

        int arr[] = new int[100000001];
        long startTime = System.currentTimeMillis();
        Thread[] threads = new Thread[20];

        for(int i = 0 ; i<20; i++) {
            int startIndex = 5000000 * i + 1 ;
            threads[i] = new Thread( () -> {
                for(int j = startIndex ; j< startIndex + 5000000; j++) {
                    arr[j] = j;
                }
            });
            threads[i].start();
        }

        long executionTime = System.currentTimeMillis() - startTime;

        System.out.println("멀티 스레드 실행 시간 : " + executionTime + " milliseconds");

        for(Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        Assertions.assertArrayEquals(arrCheck , arr);
    }
}

결론

단일스레드로 48ms 걸렸던 로직이 10개의 멀티쓰레드 실행으로 3ms 가 되었다.

멀티스레드로 성능은 향상이 되었지만 데드락 , 경합 , 스레드 오버헤드 등의

부가적인 이슈가 있으므로 "잘 사용해야할 것 같다"

profile
#SQLD강사 #AI개발 #AI강사 #개발자 개발도 하고 강의도 하지만 고민을 제일 많이 합니다

0개의 댓글