Java multithreading--thread break

Source: Internet
Author: User

2. How to terminate a thread

The Stop () and Suspend () methods in thread are not recommended for use because of inherent insecurity!
Next, I will discuss the termination mode of the thread in "blocking state" and "running state" separately, then summarize a common way.

2.1 Terminating a thread in a "blocked state"

Typically, we terminate a thread that is in a "blocking state" by means of an "interrupt".
When a thread enters a blocking state due to a call to sleep (), wait (), join (), and so on, the thread's interrupt token is set to True if the interrupt () of the calling thread is at this time. Because it is in a blocking state, the interrupt token is cleared and a interruptedexception exception is generated. You can terminate the thread by placing the interruptedexception as appropriate, in the following form:

@Overridepublic void Run () {    try {while        (true) {            //Execute task ...        }    } catch (Interruptedexception IE) {
   //the thread terminates because of a interruptedexception exception, exiting the while (true) loop!    }}

Description : In while (true), the interrupt () of the calling thread produces a interruptedexception interrupt when the thread is in a blocking state. The interrupted capture is outside the while (true) and exits the while (true) loop!
Note: The capture of the interruptedexception is typically placed outside of the while (true) loop body, which exits the while (true) loop when an exception is generated. Otherwise, the interruptedexception is within the while (true) loop body and requires additional exit processing to be added. the form is as follows:

@Overridepublic void Run () {while    (true) {        try {            //Execute task ...        } catch (Interruptedexception IE) {              //In Terruptedexception in the while (true) loop body.            //When the thread generates an Interruptedexception exception, while (true) continues to run! Need to manually exit break;}}}    

Description: The capture of the above Interruptedexception exception is within Whle (true). When a interruptedexception exception is generated, it is still in the while (true) loop, outside of the catch process, and an additional operation to exit while (true) is required to exit the while (true) loop body; Not indicated in the original text ) However, it is important to note that this added extra action (such as break) does not terminate the thread, but exits the while loop, because the code above does not give the code to continue execution, so the thread terminates normally. Rather than calling the interrupt () method to catch an abnormally terminated.

2.2 Terminating a thread in a "running state"

Typically, we terminate a thread that is in a "running state" by means of a "token". This includes " Break markers " and " extra tagging ".
(01) Terminates the thread with an "interrupt token".
The form is as follows:

@Overridepublic void Run () {while    (!isinterrupted ()) {        //Execute task ...    }}

description : isinterrupted () is a thread that determines if the interrupt token is true. When the thread is in a running state and we need to terminate it, the interrupt () method of the thread can be called, and the interrupt token with the thread is true, that is, isinterrupted () returns True. At this point, you exit the while loop.
Note: interrupt () does not terminate a thread that is in a "Running state"! It sets the interrupt token for the thread to true.

(02) through "Additional tagging".
The form is as follows:

Private volatile Boolean flag= true;protected void Stoptask () {    flag = false;} @Overridepublic void Run () {while    (flag) {        //Execute task ...    }}

Description : There is a flag tag in the thread, its default value is true, and we provide stoptask () to set the flag flag. When we need to terminate the thread, invoking the thread's Stoptask () method allows the thread to exit the while loop.
Note: The flag is defined as a volatile type to guarantee the visibility of the flag. This thread can see the value of the modified flag after other threads have modified flag through Stoptask ().

Synthetic threads are in the "blocking state" and "Run State" termination mode, and the common termination thread is compared in the following form:

@Overridepublic void Run () {    try {        //1. isinterrupted () guarantees that the thread is terminated as long as the interrupt is marked as true. While        (!isinterrupted ()) {            //Perform task ...        }    } catch (Interruptedexception IE) {          //2. The interruptedexception exception guarantees that the thread is terminated when the interruptedexception exception is generated.    }}
3. Example of terminating a thread

Interrupt () is often used to terminate a "blocking state" thread. Refer to the following example:

Demo1.java Source Class MyThread extends Thread {public MyThread (String name) {super (name);            } @Override public void Run () {try {int i=0;                while (!isinterrupted ()) {thread.sleep (100);//Hibernate 100ms i++;              System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") loop" + i); }} catch (Interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName () + "(" +this.ge Tstate () + ") Catch interruptedexception.");}} public class Demo1 {public static void main (string[] args) {try {Thread T1 = new MyThread ("T1"  );              New "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is new.");                      T1.start ();              Start "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is started.");            The main thread sleeps 300ms, then the main thread gives T1 an "interrupt" instruction. Thread.sLeep (300);            T1.interrupt ();            System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted.");            The main thread sleeps 300ms and then looks at the status of the T1.            Thread.Sleep (300); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted now.");        catch (Interruptedexception e) {e.printstacktrace (); }    } }

Operation result :

T1 (NEW) is New.t1 (RUNNABLE) are started.t1 (RUNNABLE) loop 1t1 (RUNNABLE) loop 2t1 (timed_waiting) is Interrupted.t1 (RUN nable) Catch Interruptedexception.t1 (TERMINATED) is interrupted Now.<span style= "font-family: ' Courier New '! Important FONT-SIZE:12PX!important; line-height:1.5!important; Color:rgb (0, 0, 0); " ></span>

Result Description :
(01) Thread T1 is created through new MyThread ("T1") in main thread main, followed by T1.start () to start thread T1.
After the T1 is started, its interrupt flag is constantly checked, and if the interrupt is marked "false" then hibernate 100ms.
(t1) After hibernation, it switches to main thread main, and when the main thread runs again, the thread T1 in T1.interrupt () is executed. T1 after receiving the interrupt instruction, the T1 's interrupt token is set to "false" and the Interruptedexception exception is thrown. In the T1 run () method, an exception is caught outside the loop body while the loop is terminated.

We have made minor changes to the above results, moving the code block that captures the interruptedexception exception in the Run () method into the while loop body.

Demo2.java Source Class MyThread extends Thread {public MyThread (String name) {super (name);        } @Override public void Run () {int i=0; while (!isinterrupted ()) {try {thread.sleep (100);//Hibernate 100ms} catch (Interruptedex Ception IE) {System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") Catch Interrup            Tedexception. ");            i++;          System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") loop" + i); }}}public class Demo2 {public static void main (string[] args) {try {Thread T1 = new Mythre  AD ("T1");              New "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is new.");                      T1.start ();              Start "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is started.");            The main thread sleeps 300ms, then the main thread gives T1 an "interrupt" instruction. Thread.Sleep (300);            T1.interrupt ();            System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted.");            The main thread sleeps 300ms and then looks at the status of the T1.            Thread.Sleep (300); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted now.");        catch (Interruptedexception e) {e.printstacktrace (); }    } }

Operation result :

T1 (NEW) is New.t1 (RUNNABLE) are started.t1 (RUNNABLE) loop 1t1 (RUNNABLE) loop 2t1 (timed_waiting) is Interrupted.t1 (RUN nable) Catch Interruptedexception.t1 (RUNNABLE) loop 3t1 (RUNNABLE) loop 4t1 (RUNNABLE) loop 5t1 (timed_waiting) is Interr upted now.t1 (RUNNABLE) loop 6t1 (RUNNABLE) loop 7t1 (RUNNABLE) loop 8t1 (RUNNABLE) loop 9...<span style= "font-family: ' Courier New '!important; FONT-SIZE:12PX!important; line-height:1.5!important; Color:rgb (0, 0, 0); " ></span>

Result Description :
The program entered the dead loop!
Why is that? This is because the T1 is interrupted by the interrupt () when the "Waiting (blocking) state" occurs, and the interrupt token is cleared [that is, isinterrupted () returns false] and the interruptedexception exception is thrown [ The exception is captured in the while loop body]. As a result, T1 will naturally enter the cycle of death.
To solve this problem, we need to exit the while loop for additional processing when catching an exception. For example, adding a break or return in the Mythread catch (interruptedexception) resolves the problem.

The following is an example of a thread that terminates the state state by adding additional tokens:

Demo3.java Source Class MyThread extends Thread {Private volatile boolean flag= true;    public void Stoptask () {flag = false;    } public MyThread (String name) {super (name);                } @Override public void Run () {synchronized (this) {try {int i=0;                    while (flag) {thread.sleep (100);//Sleep 100ms i++;                  System.out.println (Thread.CurrentThread (). GetName () + "(" +this.getstate () + ") loop" + i); }} catch (Interruptedexception IE) {System.out.println (Thread.CurrentThread (). GetName () + "( "+this.getstate () +") Catch interruptedexception. ");}}} public class Demo3 {public static void main (string[] args) {try {MyThread T1 = new MyThread ("t  1 ");              New "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is new.");                T1.start ();      Start "Thread T1" System.out.println (t1.getname () + "(" +t1.getstate () + ") is started.");            The main thread sleeps 300ms, then the main thread gives T1 an "interrupt" instruction.            Thread.Sleep (300);            T1.stoptask ();            System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted.");            The main thread sleeps 300ms and then looks at the status of the T1.            Thread.Sleep (300); System.out.println (T1.getname () + "(" +t1.getstate () + ") is interrupted now.");        catch (Interruptedexception e) {e.printstacktrace (); }    } }

Operation result :

T1 (NEW) is New.t1 (RUNNABLE) are started.t1 (RUNNABLE) loop 1t1 (RUNNABLE) loop 2t1 (timed_waiting) is Interrupted.t1 (RUN Nable) Loop 3t1 (TERMINATED) is interrupted Now.<span style= "font-family: ' Courier New '!important; FONT-SIZE:12PX!important; line-height:1.5!important; Color:rgb (0, 0, 0); " ></span>

4. The difference between interrupted () and isinterrupted ()

Finally, talk about interrupted () and isinterrupted ().
Both interrupted () and isinterrupted () can be used to detect the "interrupt token" of an object.
The difference is that interrupted (), in addition to returning the interrupt token, clears the interrupt token (setting the interrupt token to false), and isinterrupted () simply returns the interrupt token.






Java multithreading--thread break

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.