실행자, ExecutorService, 실행자 - 1

"안녕, 아미고!"

"처음 생성될 때 완벽한 것은 없습니다. 스레드도 마찬가지입니다. 시간이 지나면서 Java 제작자는 Runnable 인터페이스의 단점을 확신하게 되었습니다. 예외 발생을 지원하지 않았고 작업 실행 결과…"

"Runnable 인터페이스는 한 번에 12개를 실행한 다음 결과를 수집하려는 작은 하위 작업보다 대규모 독립 작업에 더 적합합니다."

"그래서 Callable 인터페이스가 발명되었습니다. 부분적으로는 일반 인터페이스이기 때문에 RunnableThread 보다 작은 작업의 병렬 실행에 훨씬 더 적합합니다."

"인터페이스의 일반적인 구현은 다음과 같습니다."

class ReverseString implements Callable<String>
{
 String str;

 ReverseString(String str)
 {
  this.str = str;
 }

 public String call() throws Exception
 {
  StringBuilder builder = new StringBuilder(str);
  builder.reverse();
  return builder.toString();
 }
}

" Runnable 과 달리 여기에서는 type 인수로 지정된 유형의 결과를 반환하는 call 메서드를 재정의해야 합니다. 이 접근 방식은 void를 반환하는 Runnable 인터페이스의 run 메서드보다 훨씬 편리합니다. 때때로 개발자는 스레드의 결과를 얻기 위한 다양한 해결 방법."

"알겠어요."

"이제 Callable이 ThreadPoolExecutor와 함께 작동하는 방법을 살펴보십시오.

"먼저 ThreadPoolExecutor 클래스의 submit 메서드는 매개변수화된 Future 개체를 반환합니다. 이 개체를 사용하여 작업이 완료되었는지 확인하고 결과를 얻을 수 있습니다."

"작동 방식은 다음과 같습니다."

// 1. Create a ThreadPoolExecutor
ExecutorService service = Executors.newFixedThreadPool(5);

// 2. Add a task to it
Future<String> task = service.submit(new ReverseString("Amigo"));

// 3. Wait until the task is done
while(!task.isDone())
{
 Thread.sleep(1);
}

// 4. Try to get the result
//We will get either the result, or an exception if one occurred while the task was being executed
try
{
 System.out.println("Full string : " + task.get());
}
catch (Exception ie)
{
 ie.printStackTrace(System.err);
}

// 5. Stop the ThreadPool.
service.shutdown();

"멀리 떨어져! 나는 특히 Future 클래스를 좋아합니다. 어떤 메서드가 있습니까?"

"가장 흥미로운 것은 다음과 같습니다."

방법 설명
boolean cancel(boolean mayInterrupt);
작업을 중지합니다.
boolean isCancelled();
작업이 중지된 경우 true를 반환합니다.
boolean isDone();
작업이 실행 중인 경우 true를 반환합니다.
V get() throws InterruptedException, ExecutionException;
호출 메서드의 결과를 반환하거나 예외가 발생한 경우 예외를 throw합니다.

"멋지다! 작업을 중지할 수도 있습니다."

"이것에 너무 의존하지 마세요. 모든 스레드가 멈출 수 있는 것은 아닙니다. 하지만 작업이 아직 대기열에 있으면 잘 작동할 것입니다."

"저는 이 접근 방식이 마음에 듭니다. 스레드를 직접 만든 다음 스레드에서 결과를 가져오려고 하는 것보다 훨씬 편리합니다."

"좋아요. 오늘은 여기까지 하겠습니다."