Java 7 Concurrency Cookbook Translation The first chapter of thread management

Source: Internet
Author: User

Three, break a thread

A Java program with multiple threads will end with one of two conditions: one is that all non-background threads are executed, and the other is a thread that executes the System.exit () method. You need to end a thread when you want to end a running Java program or a user of a program that wants to cancel a task that a thread is performing.

Java provides an interrupt mechanism to indicate that we want to terminate a thread. The core of this mechanism is that the thread must check if it is interrupted, and the thread itself decides whether to respond to the interrupt request. The thread can continue execution by ignoring the interrupt request.

In this tip, we will develop a program that creates a thread and uses an interrupt mechanism to end the thread after 5 seconds.

 Public classMain { Public Static voidMain (string[] args) {Thread task=NewPrimegenerator ();                Task.start (); Try{Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace ();    } task.interrupt (); }} Public classPrimegeneratorextendsThread {@Override Public voidrun () {LongNumber = 1L;  while(true) {            if(IsPrime (number)) {System.out.printf ("Number" + number + "is Prime"); }                        if(isinterrupted ()) {System.out.printf ("The Prime Generator has been interrupted"); return; } Number++; }    }        Private BooleanIsPrime (LongNumber ) {        if(Number <= 2) {            return true; }         for(Longi = 2; I < number; i++) {            if((number% i) = = 0) {                return false; }        }        return true; }}

There is a Boolean property in the thread class to indicate whether the thread corresponding to the class is interrupted. Set its corresponding thread to be interrupted by calling the interrupt () method of the Thread object. The isinterrupted () method is used to return the state of whether the corresponding thread is interrupted.

The Thread class also has a static method, Interrupted (), which also returns the status of whether the thread is interrupted. However, this method has a side effect: To reset the thread's interrupted state to false.

A thread can ignore its interrupted state, but this is usually not a good programming habit.

Iv. controlling the interrupt state of a thread

In the previous tip, you learned how to break a thread and how to control the interrupt state of a thread. If you're just going to break the execution of a simple thread, then the last secret is enough. However, if the thread implements a complex algorithm that is divided into multiple methods, or it contains a method that implements the recursive algorithm, we should use a better mechanism to go to the interrupt state of the thread. To do this, Java provides the interruptedexception. When you find that the thread is interrupted in the run () method, you can throw and catch the exception.

In this tip, our thread looks for a file with a specific name in the directory and its subdirectories, which shows how to use Interruptedexception to control thread interrupts.

 Public classFileSearchImplementsrunnable{PrivateString Initpath; PrivateString FileName;  PublicFileSearch (String initpath, String fileName) { This. Initpath =Initpath;  This. FileName =FileName; } @Override Public voidRun () {File file=NewFile (Initpath); if(File.isdirectory ()) {Try{directoryprocess (file); } Catch(interruptedexception e) {System.out.printf ("%s:the Search has been" + "interrupted", Thread.CurrentThread (). GetName ()); }        }    }        Private voidDirectoryprocess (File file)throwsinterruptedexception {File list[]=File.listfiles (); if(List! =NULL) {             for(inti = 0; i < list.length; i++) {                if(List[i].isdirectory ()) {directoryprocess (list[i]); } Else{fileprocess (list[i]); }            }        }        if(thread.interrupted ()) {Throw Newinterruptedexception (); }    }        Private voidFileprocess (File file)throwsinterruptedexception {if(File.getname (). Equals (FileName)) {System.out.printf ("%s:%s\n", Thread.CurrentThread (). GetName (), File.getabsolutepath ()); }        if(thread.interrupted ()) {Throw Newinterruptedexception (); }    }} Public classMain { Public Static voidMain (string[] args) {FileSearch search=NewFileSearch ("c:\\", "Autoexec.bat"); Thread Thread=NewThread (search);                Thread.Start (); Try{TimeUnit.SECONDS.sleep (10); } Catch(interruptedexception e) {e.printstacktrace ();    } thread.interrupt (); }}

In this example, we use the exception mechanism to achieve the purpose of terminating the thread. You run the sample program, and the program begins to traverse the directory and look for a specific file. Once the thread has checked itself out, it throws a Interruptedexception exception and continues executing the code of the Run () method, with multiple layers of recursive calls having no real effect on the result.

The sleep () method in the Java Concurrency API may also throw interruptedexception exceptions.

The author summarizes: The Essence of this secret is the thread itself check whether or not interrupted, found to be interrupted, by throwing an unusual way to jump directly to the exception capture code, whether the multi-layer recursion to this abnormal jump mechanism has no effect.

Important: This series of translation documents will also be in my public number (this mountain is my opening) the first time to publish, welcome attention.

Java 7 Concurrency Cookbook Translation The first chapter of thread management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.