Java multi-thread interrupt mechanism (how to handle interrupts?) )

Source: Internet
Author: User

First, introduce

This article mainly records the use of thread breaks in the interrupt () method, and how to handle interruptedexception. It is a cautious and skillful job to handle interruptedexception anomalies.

Due to the use of the Stop () method to stop the thread is very violent, the people thread run well, suddenly kill someone else, the thread occupied by the lock is forced to release, very easy to cause data inconsistency. Refer to this article for an introduction to the Stop () method.

Therefore, a gentle way is proposed: request another thread to stop executing, this is the interrupt mode.

Second, interruption and how to respond to interruptions?

How to gracefully respond to interrupts it's really too advanced, see this article: Java Theory and Practice: Handling interruptedexception is a shock. Here are just a few of the simplest things I understand about response interruptions.

Suppose a thread is going to keep processing something (such as I has been self-increasing), but there is a requirement: Before handling things, check that the thread is interrupted, and if it has been interrupted, the processing should end.

Here are some examples from the Java Multithreaded Core programming technology

1  Public classRun {2 3      Public Static voidMain (string[] args) {4         Try {5MyThread thread =NewMyThread ();6 Thread.Start ();7Thread.Sleep (2000);8Thread.Interrupt ();//Request Interrupt Mythread thread9}Catch(interruptedexception e) {TenSystem.out.println ("Main Catch"); One e.printstacktrace (); A         } -System.out.println ("end!"); -     } the}

After the main thread sleeps 2000ms, the execution line 8th interrupts the Mythread thread.

1  Public classMyThreadextendsThread {2 @Override3      Public voidrun () {4         Super. Run ();5          for(inti = 0; I < 500000; i++) {6             if( This. Interrupted ()) {7System.out.println ("should be stopped and exit");8                  Break;9             }TenSystem.out.println ("i=" + (i + 1)); One         } ASystem.out.println ("This is also executed. Thread does not stopped ");//Although the thread was interrupted, it did not end up running. This line of code will still be executed -     } -}

When the mythread obtains the CPU execution, the 6th line of the if test detects that the interrupt identity is set. That is, the Mythread thread detects that the main thread wants to interrupt its request.

In most cases, the Mythread detects an interrupt request, and the response to the interrupt is: Exit execution (or end execution).

However, the above line 5th to 8th for loop is the Execute break statement that jumps out for the for loop. However, the thread does not end, it just jumps out of the for loop, and it continues to execute the 12th line of code ....

So the question is, how do we end the thread when we receive the interrupt request?

One possible way is to use the return statement instead of the break statement ..... Ha ha...

Of course, a more elegant way is to throw interruptedexception exceptions.

Look at the following code for the Mythread class:

1  Public classMyThreadextendsThread {2 @Override3      Public voidrun () {4         Super. Run ();5         Try{6              for(inti = 0; I < 500000; i++) {7                 if( This. Interrupted ()) {8System.out.println ("should be stopped and exit");9                     Throw Newinterruptedexception ();Ten                 } OneSystem.out.println ("i=" + (i + 1)); A             } -SYSTEM.OUT.PRINTLN ("This line cannot is executed. Cause thread throws Exception ");//This line of statements will not be executed!!! -}Catch(interruptedexception e) { theSystem.out.println ("Catch interrupted exception"); - e.printstacktrace (); -         } -     } +}

When the Mythread thread detects that the interrupt is identified as true, the Interruptedexception exception is thrown on line 9th. This way, the thread is no longer able to execute other normal statements (for example, the 13th line statement will not be executed).

So, here's an example of how to end a thread by throwing an exception. Although the example is not very practical. The reason in this IBM blog post: we eat the interruption.

In line 14th, we catch the exception directly and then print out a bit, and the higher-level code in the call stack is unable to get information about the exception.

The E.printstacktrace () Action on line 16th is equivalent to

"It's not wise to just record interruptedexception, because it's too late to deal with it when people come to read it. ) "---Excerpt from the reference blog

Above we throw an exception in the run () method, as described here:

Sometimes it is not appropriate to throw interruptedexception, for example, when a task defined by Runnable invokes an interruptible method. in this case, interruptedexception cannot be re-thrown, but you do not want to do nothing. When a blocking method detects an interrupt and throws a interruptedexception, it clears the interrupt state. If you snap to interruptedexception but cannot re-throw it, you should keep the evidence of the interruption so that the higher-level code in the call stack knows the interrupt and responds to the interrupt. The task can be done by calling interrupt () to "re-break" the current thread, as shown in Listing 3. -----"Excerpt from the reference post"

Because, the Run method is the method implemented in the Runnable interface. It cannot be defined as follows: "Interruptedexception cannot be re-thrown".

        @Override        publicvoidthrows interruptedexception{//  This is wrong           //dosomething ...

Therefore, a better solution is interrupt() to call to "re-break" the current thread. The way to improve catch exceptions in the Mythread class is as follows:

1  Public classMyThreadextendsThread {2 @Override3      Public voidrun () {4         Super. Run ();5         Try{6              for(inti = 0; I < 500000; i++) {7                 if( This. Interrupted ()) {8System.out.println ("should be stopped and exit");9                     Throw Newinterruptedexception ();Ten                 } OneSystem.out.println ("i=" + (i + 1)); A             } -SYSTEM.OUT.PRINTLN ("This line cannot is executed. Cause thread throws Exception "); -}Catch(interruptedexception e) { the             /**It's not working . - * SYSTEM.OUT.PRINTLN ("Catch interrupted Exception"); - * E.printstacktrace (); -              */ +Thread.CurrentThread (). interrupt ();//This is a better deal. -         } +     } A}

In this way, the eat anomaly becomes a further diffusion of abnormal events.

Reference blog: Java Theory and Practice: Handling Interruptedexception

Java multi-thread interrupt mechanism (how to handle interrupts?) )

Related Article

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.