This article is a summary of the study of the article on the network, thank you for your selfless sharing.
1 , if the thread implements some method that is divided by a complex algorithm, or if his method has recursive invocation, then we can use a better mechanism to control thread interruption. interruptedexception Exceptions are provided for this Java . When you detect a program interrupt and capture it within the run() method, you can throw the exception.
2 , interruptedexception exceptions are caused by a number of concurrent API related to Java methods, such as Sleep () thrown.
The following procedure explains
Package Chapter;import java.io.file;/** * <p> * Description: The thread we will implement will find files in files and subfolders based on the given name, This will show how to use the Interruptedexception exception to control thread interrupts. * </p> * * @author Zhangjunshuai * @version 1.0 Create date:2014-8-11 pm 3:10:29 Project name:java7thread * * <pre> * Modification History: * Date Author Vers Ion Description *---------------------------------------------------------------------------------------------- -------------* Lastchange: $Date:: $ $Author: $ $Rev: $ * </pre> * */public class File Search implements Runnable {private string Initpath;private string Filename;public filesearch (String initpath, String fil ename) {this.filename = Filename;this.initpath = Initpath;} @Overridepublic void Run () {File File = new file (Initpath), if (File.isdirectory ()) {try {directoryprocess (File);} catch (I Nterruptedexception 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) {fo R (int i = 0; i < list.length; i++) {if (List[i].isdirectory ()) {directoryprocess (list[i]);} else {fileprocess (list[i]) ;}}} 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 ();}}}
Package Chapter;import Java.util.concurrent.timeunit;public class Main4 {/** * <p> * </p> * @author Zhangjunsh Uai * @date 2014-8-12 pm 3:40:54 * @param args */public static void main (string[] args) {FileSearch searcher = new Filesear CH ("c:\\", "Unintall.log"); Thread thread = new Thread (searcher), Thread.Start (), try {TimeUnit.SECONDS.sleep (ten);} catch (Interruptedexception e) { E.printstacktrace ();} Thread.Interrupt ();}}
Note that thread.interrupted () is used in the program, this method and
isInterrupted()是有区别的。
Another: JDK Timeunit is a good example of learning enumerations
Reference:
Concurrent Programming Network