Given the code fragment:
class CallerThread implements Callable<String> {
String str;
public CallerThread(String s) {
this.str = s;
}
public String call() throws Exception {
return str.concat(" Call");
}
}
and
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newFixedThreadPool(4); //line n1
Future f1 = es.submit(new CallerThread("Call"));
String str = f1.get().toString();
System.out.println(str);
}
Which statement is true?
A. The program prints Call Call and terminates.
B. The program prints Call Call and does not terminate.
C. A compilation error occurs at line n1.
D. An ExecutionException is thrown at run time.
題解
程式第 32 行,實體化出 CallerThread 的物件並透過 ExecutorService 來執行。
程式第 33 行,會等待 CallerThread 物件的 call 方法執行完畢後,將結果回傳,儲存至 str 變數中。回傳的物件為「Call Call」字串。
程式第 34 行,輸出「Call Call」。
由於沒有呼叫 ExecutorService 物件的 shutdown 相關方法,因此程式不會停止執行。
