카테고리 없음

callable runnable 차이

jw-backend 2024. 7. 24. 16:10
반응형

Callable과 Runnable은 Java에서 스레드를 실행하기 위한 두 가지 인터페이스로, 비슷한 점이 있지만 몇 가지 중요한 차이점이 있습니다. 아래에서 이 두 인터페이스의 차이점을 설명하겠습니다.

1. 반환 값

  • Callable:
    • Callable 인터페이스는 call() 메서드를 정의하며, 이 메서드는 결과값을 반환합니다. 즉, 작업이 완료되면 특정 타입의 값을 반환할 수 있습니다.
    • 예: T call() throws Exception;
  • Runnable:
    • Runnable 인터페이스는 run() 메서드를 정의하며, 이 메서드는 반환값이 없습니다. 즉, 작업이 완료되면 아무 것도 반환하지 않습니다.
    • 예: void run();

2. 예외 처리

  • Callable:
    • Callable의 call() 메서드는 체크된 예외를 던질 수 있습니다. 따라서, 예외 처리를 더 유연하게 할 수 있습니다.
  • Runnable:
    • Runnable의 run() 메서드는 체크된 예외를 던질 수 없습니다. 발생할 수 있는 예외는 반드시 처리해야 합니다.

3. 사용 예

  • Callable 사용 예:
  • java

    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 CallableExample {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(1);
            Callable<Integer> task = () -> {
                Thread.sleep(1000);
                return 123; // 결과 반환
            };
    
            Future<Integer> future = executor.submit(task);
            
            try {
                Integer result = future.get(); // 결과 얻기
                System.out.println("결과: " + result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
    
            executor.shutdown();
        }
    }
    
  • Runnable 사용 예:
  • java

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class RunnableExample {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(1);
            Runnable task = () -> {
                System.out.println("작업 실행 중");
                // 반환값이 없음
            };
    
            executor.execute(task); // Runnable 실행
            executor.shutdown();
        }
    }
    

요약

  • Callable: 반환값이 있으며, 체크된 예외를 던질 수 있는 인터페이스.
  • Runnable: 반환값이 없으며, 체크된 예외를 던질 수 없는 인터페이스.

이 두 인터페이스는 스레드를 실행하는 데 각각의 용도와 특성이 있으며, 상황에 따라 적절히 선택하여 사용할 수 있습니다.