본문 바로가기
CS

[Java] Java에서의 Thread와 Thread Pool

by kimyoungrok 2025. 2. 8.
728x90

1️⃣ 스레드(Thread)

스레드는 프로그램 내에서 실행되는 하나의 작업 단위

스레드의 특징

  • CPU의 기본 실행 단위 (프로세스 안에서 개별적으로 실행됨)
  • 각 스레드는 독립 실행 (하나의 스레드가 멈춰도 다른 스레드는 계속 실행됨)
  • 멀티 스레드를 사용하면 프로그램이 여러 작업을 동시에 실행 가능

단일 스레드 작업(Single Thread)

package pl.java.thread;

public class SingleThreadSample {
    public static void main(String[] args) {
        System.out.println("작업 1 시작");
        try { Thread.sleep(3000); } catch (InterruptedException _) {}
        System.out.println("작업 1 완료");

        System.out.println("작업 2 시작");
        try { Thread.sleep(3000); } catch (InterruptedException _) {}
        System.out.println("작업 2 완료");
    }
}

/*
작업 1 시작
작업 1 완료
작업 2 시작
작업 2 완료
*/

⚠️기본적으로 단일스레드로 작업을 하므로 병렬처리가 안 되어 작업 간 대기 시간이 존재한다.

작업1 시작 → 3초 대기 → 작업 1 완료 → 작업 2시작 → (3초 대기) → 작업 2 완료

 

멀티 스레드 작업(Multi Thread)

package pl.java.thread;

public class MultiThreadExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            System.out.println("작업 1 시작");
            try { Thread.sleep(3000); } catch (InterruptedException _) {}
            System.out.println("작업 1 완료");
        });

        Thread thread2 = new Thread(() -> {
            System.out.println("작업 2 시작");
            try { Thread.sleep(3000); } catch (InterruptedException _) {}
            System.out.println("작업 2 완료");
        });

        thread1.start();
        thread2.start();
    }
}

/*
작업 2 시작
작업 1 시작
작업 1 완료
작업 2 완료
*/

💡여러 개의 스레드를 사용해 병렬 처리를 진행할 수 있다


2️⃣ 스레드 풀(Thread Pool)

스레드를 미리 여러 개 만들어 놓고 필요할 때마다 재사용 하는 방식

왜 스레드 풀을 사용할까?

  1. 새로운 스레드를 만들면 비용(시간 & 메모리)이 크다
  2. 하나의 요청마다 새로운 스레드를 만들 때 자원이 필요하며 이는 성능 저하로 이어질 수 있다.
  3. 미리 만들어 놓은 스레드를 재사용해서 성능 최적화 가능 🔄
  4. 스레드가 필요한 경우 스레드 풀에서 스레드를 꺼내 사용하고, 다시 풀에 반환하여 불필요한 생성 비용을 줄일 수 있음

스레드 풀을 사용하지 않은 경우

package pl.java.thread;

public class NoThreadPoolExample {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName());
                try { Thread.sleep(2000); } catch (InterruptedException e) {}
            }).start();
        }
    }
}
/*
Thread-0
Thread-1
Thread-3
Thread-2
Thread-6
Thread-4
Thread-5
Thread-7
Thread-8
Thread-9
*/

💡스레드 풀을 사용하지 않았기 때문에 매번 새로운 스레드를 생성한다.

스레드 풀을 사용하는 경우

package pl.java.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        try (ExecutorService executorService = Executors.newFixedThreadPool(5)) {

            for (int i = 0; i < 10; i++) {
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " 작업 실행");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                    }
                });
            }

            executorService.shutdown(); // 스레드 풀 종료
        }
    }
}

/*
pool-1-thread-1 작업 실행
pool-1-thread-3 작업 실행
pool-1-thread-4 작업 실행
pool-1-thread-2 작업 실행
pool-1-thread-5 작업 실행
pool-1-thread-2 작업 실행
pool-1-thread-5 작업 실행
pool-1-thread-4 작업 실행
pool-1-thread-3 작업 실행
pool-1-thread-1 작업 실행
*/
  • 최대 5개의 스레드만 사용하도록 설정, 끝난 스레드는 재사용됨!
  • 새로운 스레드를 계속 생성하지 않기 때문에 성능 최적화됨.

🔥 결론

스레드는 프로그램에서 실행되는 하나의 작업 단위

멀티 스레드를 사용하면 여러 작업을 동시에 실행 가능

스레드 풀(Thread Pool)을 사용하면 스레드를 재사용하여 성능 최적화

728x90