JAVA
Executors.newFixedThreadPool()
parkit
2025. 4. 10. 23:10
728x90
반응형
Executors.newFixedThreadPool()는 Java의 동시성 프레임워크에서 제공하는 메서드로, 고정된 크기의 스레드 풀을 생성합니다. 이 메서드는 java.util.concurrent 패키지에 속한 Executors 클래스의 정적 메서드입니다.
기본 개념
- 스레드 풀: 작업 실행을 위해 미리 생성된 스레드들의 집합
- 고정 크기: 생성 시 지정된 스레드 수를 유지 (최대 스레드 수 고정)
파라미터
Executors.newFixedThreadPool() 메서드는 두 가지 오버로딩된 형태를 가집니다:
- newFixedThreadPool(int nThreads): 지정된 수의 스레드를 가진 스레드 풀 생성
- nThreads: 풀에서 유지할 스레드 수
- newFixedThreadPool(int nThreads, ThreadFactory threadFactory): 지정된 스레드 팩토리를 사용하여 스레드 풀 생성
- nThreads: 풀에서 유지할 스레드 수
- threadFactory: 새 스레드를 생성할 때 사용할 팩토리
예시 코드
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class FixedThreadPoolExample {
public static void main(String[] args) {
// 3개의 스레드를 가진 고정 크기 스레드 풀 생성
ExecutorService executor = Executors.newFixedThreadPool(3);
// 5개의 작업 제출
for (int i = 0; i < 5; i++) {
final int taskId = i;
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("Task " + taskId + " is running on " + threadName);
// 작업이 2초 동안 실행되는 것 시뮬레이션
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Task " + taskId + " completed");
return null;
});
}
// 새 작업 제출 중단
executor.shutdown();
try {
// 모든 작업이 완료될 때까지 최대 10초 대기
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
// 10초 후에도 완료되지 않은 작업 강제 종료
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
}
System.out.println("All tasks completed");
}
}
실행 결과 설명
이 코드를 실행하면 다음과 같은 결과가 나타납니다:
Task 0 is running on pool-1-thread-1
Task 1 is running on pool-1-thread-2
Task 2 is running on pool-1-thread-3
Task 0 completed
Task 1 completed
Task 3 is running on pool-1-thread-1
Task 2 completed
Task 4 is running on pool-1-thread-2
Task 3 completed
Task 4 completed
All tasks completed
실행 과정 설명:
- 3개의 스레드를 가진 고정 크기 스레드 풀을 생성합니다.
- 5개의 작업을 제출합니다.
- 처음 3개의 작업(0, 1, 2)은 즉시, 각각 다른 스레드에서 실행됩니다.
- 각 작업은 2초 동안 실행됩니다.
- 처음 3개의 작업이 완료되면, 나머지 2개의 작업(3, 4)이 가용 스레드에서 실행됩니다.
- 모든 작업이 완료된 후 "All tasks completed" 메시지가 출력됩니다.
주요 특징
- 스레드 재사용: 작업이 완료된 후 스레드는 폐기되지 않고 다음 작업을 위해 재사용됩니다.
- 작업 큐: 제출된 모든 작업은 내부 큐에 저장되며, 가용 스레드가 있을 때 실행됩니다.
- 자원 관리: 생성 시 지정된 수의 스레드만 유지하므로 과도한 스레드 생성을 방지합니다.
- 리소스 관리: shutdown()과 shutdownNow() 메서드를 통해 적절히 리소스를 정리해야 합니다.
이 메서드는 높은 동시성이 필요한 서버 애플리케이션에서 특히 유용하며, 동시에 실행할 수 있는 작업의 수를 제한하고 싶을 때 적합합니다.
728x90
반응형