Callable 인터페이스는 Runnable과 유사하지만 Runnable은 결과를 반환하지 않으며 결과를 반환 한 후에는 값을 반환 할 수 있습니다. 이 반환 값은 미래에 따라 얻을 수 있습니다
코드 사본은 다음과 같습니다.
패키지 com.future.test;
import java.io.filenotfoundException;
import java.io.ioexception;
java.util.concurrent.callable import;
import java.util.concurrent.executionException;
import java.util.concurrent.executorservice;
java.util.concurrent.executors import;
java.util.concurrent.futuretask import;
java.util.concurrent.timeUnit import;
java.util.concurrent.timeoutException import;
공개 클래스 MyTest {
// 실행 메소드에서 잡힌 예외를 수신 한 다음 사용자 정의 메소드가 예외를 던집니다.
// 비공개 정적 던지기 예외;
/**
* @param args
*/
public static void main (String [] args) {
// TODO 자동 생성 메소드 스텁
문자열 결과 = "";
ExecutorService Executor = Executor.NewsingLethreadExecutor ();
FutureTask <string> Future =
New FutureTask <string> (new Callable <string> () {// 호출 가능한 인터페이스를 생성자 매개 변수로 사용합니다.
public String Call () {
// 실제 작업은 여기에서 실행됩니다. 여기서 리턴 값 유형은 String이며 모든 유형 일 수 있습니다.
노력하다 {
Thread.sleep (10000);
} catch (InterruptedException e) {
// TODO 자동 생성 캐치 블록
// 예외 = e;
//e.printstacktrace ();
}
"11111"을 반환합니다.
}});
Executor.Execute (미래);
// 여기서 다른 일을 할 수 있습니다
노력하다 {
result = future.get (5000, TimeUnit.milliseconds); // 타임 아웃 실행 시간을 5 초로 설정하십시오. 미래.get ()를 사용하여 실행 시간 초과를 설정하지 않고 결과를 얻을 수도 있습니다.
} catch (InterruptedException e) {
//system.out.println("task가 취소되었습니다 ");
미래 .cancel (true);
} catch (executionException e) {
미래 .cancel (true);
} catch (timeoutException e) {
미래 .cancel (true);
} 마지막으로 {
executor.shutdown ();
}
System.out.println ( "결과 :"+결과);
}
/* public void trashException ()는 filenotfoundException, ioException {
if (filenotfoundException의 예외 인스턴스)
던지기 (filenotfoundException) 예외;
if (예외 IoException의 예외)
던지기 (ioexception) 예외;
}*/
}