시나리오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 가 되었다.
멀티스레드로 성능은 향상이 되었지만 데드락 , 경합 , 스레드 오버헤드 등의
부가적인 이슈가 있으므로 "잘 사용해야할 것 같다"