Given the code fragment:
public class FileThread implements Runnable {
String fName;
public FileThread(String fName) {
this.fName = fName;
}
public void run() {
System.out.println(fName);
}
public static void main(String[] args) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Stream<Path> listOfFiles = Files.walk(Paths.get("Java Projects"));
listOfFiles.forEach(line -> {
executor.execute(new FileThread(line.getFileName().toString())); //line n1
});
executor.shutdown();
executor.awaitTermination(5, TimeUnit.DAYS); //line n2
}
}
The Java Projects directory exists and contains a list of files.
What is the result?
A. The program throws a runtime exception at line n2.
B. The program prints files names concurrently.
C. The program prints files names sequentially.
D. A compilation error occurs at line n1.
题解
Files 类别的 walk 方法可以使用深度优先(depth-first)来走访传入的文件路径。
ExecutorService 对象的 execute 方法可以使用新的线程来运行传入的 Runnable 对象。shutdown 方法可以关闭 ExecutorService 对象使其不再接受新的运行对象(Runnable 或是 Callable),但并不会等待目前正在运行和正在排队的工作运行完毕。awaitTermination 方法可以指定一个上限时间来等待 ExecutorService 对象将所有的工作处理完成。
所以这题答案是选项 B。
