Given the code fragments:
class Caller implements Callable<String> {
String str;
public Caller(String s) {
this.str = s;
}
public String call() throws Exception {
return str.concat(" Caller");
}
}
class Runner implements Runnable {
String str;
public Runner(String s) {
this.str = s;
}
public void run() {
System.out.println(str.concat(" Runner"));
}
}
and
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newFixedThreadPool(2);
Future f1 = es.submit(new Caller("Call"));
Future f2 = es.submit(new Runner("Run"));
String str1 = (String) f1.get();
String str2 = (String) f2.get();//line n1
System.out.println(str1 + " : " + str2);
}
What is the result?
A. The program prints:
Run Runner
Call Caller : null
Call Caller : null
And the program does not terminate.
B. The program terminates after printing:
Run Runner
Call Caller : Run
Call Caller : Run
C. A compilation error occurs at line n1.
D. An Execution is thrown at run time.
題解
程式第 52 行,會建立最多可以擁有兩個執行緒的 ExecutorService。
程式第 53 行,會建立 Caller 物件,並使用新的執行緒去執行 Caller 物件的 call 方法。
程式第 54 行,會建立 Runnable 物件,並使用新的執行緒去執行 Runnable 物件的 run 方法。
程式第 55 行,會等待呼叫 Caller 物件的 call 方法的執行緒是否已經執行完畢,接著回傳 call 方法的回傳值。
程式第 56 行,會等待呼叫 Runnable 物件的 run 方法的執行緒是否已經執行完畢,接著回傳 null。
在程式第 54 行至 56 行之間,某條 ExecutorService 的執行緒會執行到 Runnable 物件的 run 方法內的第 23 行,輸出「Run Runner」。
程式第 57 行,輸出「Call Caller : null」。
