□ 단점
- 새로운 스레드를 생성함으로 리소스 낭비가 발생
- 스레드 생성 비용이 비쌈
- OS의 스레드 관리 부담이 커질 수 있음
- Thread생성을 통한 비동기 처리
public static void main(String[] args) {
final long startTime = System.currentTimeMillis();
for(int i = 0; i < 5; i++){
int finalI = i;
new Thread(
() -> {
try {
log.info("{}번째 작업 {}, 소요시간: {}", finalI, plus(), System.currentTimeMillis() - startTime);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
).start();
}
log.info("메인 스레드 실행");
}
private static double plus() throws InterruptedException {
double a = Math.round(random() * 10);
double b = Math.round(random() * 10);
Thread.sleep(100);
return a + b;
}
- 결과
- thread.start()를 하게되면 실행 요청을 하게되고 OS스케줄러의 제어를 받음
- for문을 빠르게 빠져나와 메인 스레드가 먼저 실행됨
- 비동기적으로 각 쓰레드에서 요청되었던 작업이 동시에 동작함
- 일반적인 실행
public static void main(String[] args) throws InterruptedException {
final long startTime = System.currentTimeMillis();
for(int i = 0; i < 5; i++){
int finalI = i;
log.info("{}번째 작업 {}, 소요시간: {}", finalI, plus(), System.currentTimeMillis() - startTime);
}
log.info("메인 스레드 실행");
}
private static double plus() throws InterruptedException {
double a = Math.round(random() * 10);
double b = Math.round(random() * 10);
Thread.sleep(100);
return a + b;
}
- 결과
- 순차적으로 작업 진행
- 앞서 실행된 작업이 완료된 후 다음작업 실행
'Java & Spring > Java' 카테고리의 다른 글
Java - 비동기처리(CompletableFuture) (0) | 2025.03.06 |
---|---|
Java - 비동기 처리(ExecutorService / Future) (0) | 2025.03.04 |
HTTP 요청과 응답에 사용되는 클래스들 (0) | 2025.02.06 |
csv파일으로 더미데이터 생성하기 (0) | 2024.11.08 |
18일차 - Java강의(쓰레드 명령어) (0) | 2024.08.07 |