ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] Callable, Future, Executors, invokeAll() and invokeAny()
    카테고리 없음 2023. 7. 16. 22:48

    Thread와 Runnable 을 사용하여 스레드를 사용하기엔 너무 저수준의 API를 사용해야 하며, 관리가 어렵고 스레드의 수행 결과를 반환하는 것이 불가능하다.

    이를 해결하기 위해 Java5에서 추가된 Callable과 Future 를 사용하는데, 간단한 사용법은 다음과 같다.

     

    import java.util.Arrays;
    import java.util.List;
    import java.util.concurrent.*;
    
    public class Main {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            usageCallable();
        }
    
        public static void usageCallable() throws InterruptedException, ExecutionException {
            MyCallable myTask1 = new MyCallable("Hello", 1);
            MyCallable myTask2 = new MyCallable("world", 2);
    
            ExecutorService service1 = Executors.newFixedThreadPool(2);
            Future<String> future1 = service1.submit(myTask1);
            Future<String> future2 = service1.submit(myTask2);
            service1.shutdown();
    
            System.out.println("future1: " + future1.get());
            System.out.println("future2: " + future2.get());
    
    
            // InvokeAll
            ExecutorService service2 = Executors.newFixedThreadPool(2);
            List<Future<String>> invokeAllResult = service2.invokeAll(Arrays.asList(myTask1, myTask2));
            service2.shutdown();
            for (Future<String> s: invokeAllResult) {
                System.out.println("invokeAll: " + s.get());
            }
    
            // InvokeAny
            ExecutorService service3 = Executors.newFixedThreadPool(2);
            String invokeAnyResult = service3.invokeAny(Arrays.asList(myTask1, myTask2));
            service3.shutdown();
            System.out.println("invokeAny: " + invokeAnyResult);
        }
    }
    
    class MyCallable implements Callable<String> {
    
        private String input;
        private int interval;
    
        public MyCallable(String input, int interval) {
            this.input = input;
            this.interval = interval;
        }
    
        @Override
        public String call() {
            return input + " - " + interval;
        }
    }

     

     

     

Designed by Tistory.