Programming/JAVA
자바 ExecutorService 메서드
khj1999
2024. 10. 22. 21:40
Java의 ExecutorService
인터페이스는 멀티스레딩 작업을 효율적으로 처리할 수 있는 다양한 메서드를 제공한다
1. submit() 메서드
submit()
메서드는 단일 Callable
작업 또는 Runnable
작업을 제출하고
작업이 완료된 후 결과를 받을 수 있는 Future
객체를 반환.
사용법 및 특징
Callable
또는Runnable
작업을 제출.- 작업의 결과를 나타내는
Future
객체를 반환. Runnable
작업을 제출할 경우Future.get()
메서드는null
을 반환.
예제 코드
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class SubmitExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Callable<String> task = () -> {
Thread.sleep(1000);
return "작업 완료";
};
Future<String> future = executorService.submit(task);
try {
// 작업 결과를 가져옴
String result = future.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
2. invokeAny() 메서드
invokeAny()
메서드는 여러 개의 Callable
작업을 제출하고, 가장 먼저 완료된 작업의 결과를 반환.
만약 어떤 작업도 완료되지 않거나 예외가 발생할 경우, ExecutionException
이 발생.
사용법 및 특징
- 여러 개의
Callable
작업을 동시에 실행. - 가장 먼저 완료된 작업의 결과를 반환.
- 예외가 발생할 경우 해당 예외를 감싸서
ExecutionException
을 발생시킴. - 작업이 모두 완료되지 않더라도, 하나의 작업이 완료되는 즉시 결과를 반환.
예제 코드
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class InvokeAnyExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Callable<String>> tasks = Arrays.asList(
() -> {
Thread.sleep(2000);
return "Task 1 completed";
},
() -> {
Thread.sleep(1000);
return "Task 2 completed";
},
() -> {
Thread.sleep(3000);
return "Task 3 completed";
}
);
try {
// 가장 먼저 완료된 작업의 결과를 가져옴
String result = executorService.invokeAny(tasks);
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
3. invokeAll() 메서드
invokeAll()
메서드는 여러 개의 Callable
작업을 제출하고, 모든 작업이 완료될 때까지 대기함.
모든 작업의 결과를 포함하는 Future
객체의 리스트를 반환.
사용법 및 특징
- 모든 작업이 완료될 때까지 대기.
- 모든 작업의 결과를 담은
Future
리스트를 반환. - 각
Future
객체를 통해 개별 작업의 결과를 확인할 수 있다.
예제 코드
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class InvokeAllExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Callable<String>> tasks = Arrays.asList(
() -> {
Thread.sleep(2000);
return "Task 1 completed";
},
() -> {
Thread.sleep(3000);
return "Task 2 completed";
},
() -> {
Thread.sleep(1000);
return "Task 3 completed";
}
);
try {
// 모든 작업이 완료될 때까지 대기
List<Future<String>> results = executorService.invokeAll(tasks);
for (Future<String> future : results) {
try {
System.out.println(future.get());
} catch (ExecutionException e) {
System.out.println("작업 실행 중 예외 발생: " + e.getCause());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
4. shutdown() 메서드
shutdown()
메서드는 ExecutorService
의 작업을 중단하고, 더 이상 작업을 받지 않도록 한다.
현재 진행 중인 작업은 완료되며, 새로운 작업은 수락되지 않는다.
사용법 및 특징
- 실행 중인 작업이 종료될 때까지 대기.
- 새로운 작업은 수락하지 않음.
예제 코드
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ShutdownExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
// 작업 제출
executorService.submit(() -> {
try {
Thread.sleep(2000);
System.out.println("작업 완료");
} catch (InterruptedException e) {
System.out.println("작업이 중단되었습니다.");
}
});
// ExecutorService 종료
executorService.shutdown();
System.out.println("ExecutorService 종료");
}
}
5. shutdownNow() 메서드
shutdownNow()
메서드는 ExecutorService
를 즉시 종료한다.
현재 실행 중인 작업을 중단하려고 시도하고, 대기 중인 작업을 취소 함.
사용법 및 특징
- 현재 실행 중인 작업을 중단하려고 시도.
- 대기 중인 작업이 있는 경우 이들을 취소 함.
예제 코드
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ShutdownNowExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
// 작업 제출
executorService.submit(() -> {
try {
Thread.sleep(5000);
System.out.println("작업 완료");
} catch (InterruptedException e) {
System.out.println("작업이 중단되었습니다.");
}
});
// 즉시 종료
executorService.shutdownNow();
System.out.println("ExecutorService 즉시 종료");
}
}
6. isShutdown() 및 isTerminated() 메서드
isShutdown()
:ExecutorService
가 종료 상태인지 여부를 확인한다.isTerminated()
: 모든 작업이 완료된 후 종료 상태인지 여부를 확인한다.
결론
Java의 ExecutorService
는 멀티스레딩을 보다 쉽게 관리할 수 있는 다양한 메서드를 제공한다.