Java & Spring/Java

Java - 비동기 처리(Thread & Runnable)

DJ.Kang 2025. 3. 4. 06:30

□ 단점

  • 새로운 스레드를 생성함으로 리소스 낭비가 발생
  • 스레드 생성 비용이 비쌈
  • 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;
    }

 

- 결과

  • 순차적으로 작업 진행
  • 앞서 실행된 작업이 완료된 후 다음작업 실행