Java Thread interrupt thread control

Description

Java Thread interrupt thread control


import java.io.File;
import java.util.concurrent.TimeUnit;

/**/*from  w  w w.  j  av  a2s .c om*/
 * Search for the autoexect.bat file on the Windows root folder and its sub
 * folders during ten seconds and then, interrupts the Thread
 */
public class Main {

  public static void main(String[] args) {
    // Creates the Runnable object and the Thread to run it
    FileSearch searcher = new FileSearch("C:\\", "autoexec.bat");
    Thread thread = new Thread(searcher);

    // Starts the Thread
    thread.start();

    // Wait for ten seconds
    try {
      TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Interrupts the thread
    thread.interrupt();
  }

}

class FileSearch implements Runnable {

  private String initPath;

  private String fileName;

  public FileSearch(String initPath, String fileName) {
    this.initPath = initPath;
    this.fileName = fileName;
  }

  @Override
  public void run() {
    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());
        cleanResources();
      }
    }
  }

  private void cleanResources() {

  }

  private void directoryProcess(File file) throws InterruptedException {

    // Get the content of the directory
    File list[] = file.listFiles();
    if (list != null) {
      for (int i = 0; i < list.length; i++) {
        if (list[i].isDirectory()) {
          // If is a directory, process it
          directoryProcess(list[i]);
        } else {
          // If is a file, process it
          fileProcess(list[i]);
        }
      }
    }
    // Check the interruption
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
  }

  private void fileProcess(File file) throws InterruptedException {
    // Check the name
    if (file.getName().equals(fileName)) {
      System.out.printf("%s : %s\n", Thread.currentThread().getName(), file.getAbsolutePath());
    }

    // Check the interruption
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
  }

}



PreviousNext

Related