Callable과 Future

이승민·2022년 10월 18일
0

JAVA8

목록 보기
17/18

Callable

  • Runable과 유사하지만 작업의 결과를 받을 수 있다.

Future

  • 비동기적인 작업의 현재 상태를 조회하거나 결과를 가져올 수 있다.

결과 가져오기 get()

  • 블로킹 콜이다
  • 타임아웃(최대한으로 기다릴 시간)을 설정할 수 있다.
public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<String> hello = () -> {
            Thread.sleep(2000L);
            return "Hello";
        };

        Future<String> submit = executorService.submit(hello);
        System.out.println("Started!!");

        submit.get();

        System.out.println("End!!");

    }

작업 상태 확인하기 isDone()

  • 완료 했으면 true 아니면 false를 리턴한다.

작업 취소하기 cancle()

  • 취소 했으면 true 못했으면 false를 리턴한다.
  • Parameter로 true를전달하면 현재 진행중인 쓰레드를 interrput하고 그러지 않으면 현재 진행중인 작업이 끝날떄까지 기다린다.
  • cancle이 되고 isDone()을 호출하면 true를 리턴된다.

여러 작업 동시에 실행하기 invokeAll()

  • 동시에 실행한 작업 중에 제일 오래 걸리는 작업 만큼 시간이 걸린다
  		ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<String> hello = () -> {
            Thread.sleep(2000L);
            return "Hello";
        };

        Callable<String> the = () -> {
            Thread.sleep(3000L);
            return "the";
        };

        Callable<String> java = () -> {
            Thread.sleep(1000L);
            return "java";
        };

        List<Future<String>> futures = executorService.invokeAll(Arrays.asList(hello, the, java));
        for(Future<String> f : futures){
            System.out.println(f.get());

        }

        executorService.shutdown();

여러 작업 중에 하나라도 먼저 응답이 오면 끝내기 invokeAny()

  • 동시에 실행한 작업 중에 제일 짧게 걸리는 작업만큼 시간이 걸린다
  • 블록킹 콜이다
ExecutorService executorService = Executors.newFixedThreadPool(4);

        Callable<String> hello = () -> {
            Thread.sleep(2000L);
            return "Hello";
        };

        Callable<String> the = () -> {
            Thread.sleep(3000L);
            return "the";
        };

        Callable<String> java = () -> {
            Thread.sleep(1000L);
            return "java";
        };

        String s = executorService.invokeAny(Arrays.asList(hello, the, java));

        System.out.println(s);

        executorService.shutdown();
```![](https://velog.velcdn.com/images/lee2963/post/2b908588-490b-4910-9c3a-86bd17421898/image.jpeg)
profile
💻 끊임없이 성장하는 백엔드 개발자 💻

0개의 댓글