Skip to content

Instantly share code, notes, and snippets.

@paullewallencom
Created June 7, 2018 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paullewallencom/ae6cf684de0265598d86635a6ffac945 to your computer and use it in GitHub Desktop.
Save paullewallencom/ae6cf684de0265598d86635a6ffac945 to your computer and use it in GitHub Desktop.
Controlling the Interruption of a Thread
package Example03;
import java.io.File;
public 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();
}
}
}
// Controlling the interruption of a thread
package Example03;
import java.util.concurrent.TimeUnit;
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment