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」。
