-
Callable과 Future자바/자바8 2022. 3. 17. 05:54
Callable
- Runnable과 유사하지만 작업의 결과를 받을 수 있다.
Future
- 비동기적인 작업의 현재 상태를 조회하거나 결과를 가져올 수 있다.
Callable을 사용한 작업
- 작업상태 확인하기: future.isDone()
- 작업 취소하기: future.cancel()
- 여러 작업 동시에 실행하기: executorService.invokeAll(Arrays.asList(hello, hello2, hello3));
- 여러 작업 중에 하나라도 먼저 응답이 오면 끝내기: executorService.invokeAny(Arrays.asList(hello, hello2, hello3));
long start = System.currentTimeMillis(); ExecutorService executorService = Executors.newSingleThreadExecutor(); Callable<String> hello = new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(2000L); System.out.println((System.currentTimeMillis()-start)/1000+"초가 지났습니다."); System.out.println(Thread.currentThread().getName()); return "Hello"; } }; Future<String> future = executorService.submit(hello); System.out.println("start status: "+future.isDone()); String h = future.get();// 블록킹콜 System.out.println(h); System.out.println("end status: "+future.isDone()); Thread.sleep(10000); executorService.shutdown();
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
Future (Java Platform SE 8 )
Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task
docs.oracle.com
'자바 > 자바8' 카테고리의 다른 글
스트림 (0) 2022.05.01 2. 자바에서 제공하는 함수형 인터페이스 (0) 2022.03.18 Executor (0) 2022.03.17 1. 함수형 인터페이스와 람다 표현식 소개 (0) 2022.03.11 0. 자바8 학습의 필요성 (0) 2022.03.11