Created
June 7, 2018 22:48
-
-
Save paullewallencom/ae6cf684de0265598d86635a6ffac945 to your computer and use it in GitHub Desktop.
Controlling the Interruption of a Thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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