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。