上一节所说的中断机制能用在简单的场景。但应用在复杂场景(如算法较复杂需要分解成多个方法、有递归调用等情况)时,有一个更好的机制。 您可抛出 InterruptedException 异常并在 run() 方法中捕获此异常。
线程类 (FileSearch)
private String initPath; private String fileName; public FileSearch(String initPath, String fileName) { this.initPath = initPath; this.fileName = fileName; }
File file = new File(initPath); if (file.isDirectory()) { try { directoryProcess(file); } catch (InterruptedException e) { System.out.printf("%s: The search has been interrupted", Thread.currentThread().getName()); } }
private void directoryProcess(File file) throws InterruptedException { File list[] = file.listFiles(); if (list != null) { for (File aList : list) { if (aList.isDirectory()) { directoryProcess(aList); } else { fileProcess(aList); } } } if (Thread.interrupted()) { throw new InterruptedException(); } }
private void fileProcess(File file) throws InterruptedException { if (file.getName().equals(fileName)) { System.out.printf("%s : %s\n", Thread.currentThread().getName(), file.getAbsolutePath()); } if (Thread.interrupted()) { throw new InterruptedException(); } }
控制类 (Main)
FileSearch searcher = new FileSearch("C:\\", "autoexec.bat"); Thread thread = new Thread(searcher); thread.start();
try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt();