Java multithreaded Programming--How to terminate a thread

Source: Internet
Author: User

1. The stop () function of the thread.stop () function terminates the thread as if it were forced to unplug the power cord, which may pose an unknown risk, so it is no longer recommended. Please forget it ~ ~
2. Change the flag variable status

Typically, we use a flag variable in the thread to control the running of threads, such as:

public class Testcallable implements Runnable {Private Boolean running = true;    public void Stop () {this.running = false; } public void Run () {try {BufferedReader reader = new BufferedReader (New InputStreamReader (SYSTEM.I            n));                while (running) {System.out.println ("thread is running ...");            Thread.Sleep (20000);        } System.out.println ("Thread is terminated.");        } catch (IOException e) {e.printstacktrace ();            }} public static void Main (string[] args) {try {testcallable callable = new testcallable ();            Thread th = new thread (callable);            Th.start ();            Thread.Sleep (1000);            Callable.stop (); SYSTEM.OUT.PRINTLN ("The terminated thread command has been released.        ");        } catch (Exception e) {e.printstacktrace (); }    }}
Execution of the above code can be found that the thread is blocked at Reader.readline (), even if the main thread changes the flag variable, but does not immediately end the child thread, only wait for the block to be broken, and run to the next loop condition to determine the time to terminate. So when you use this method, you should consider blocking the situation. Of course, this approach is good if the operations within the entire loop belong to the same transaction.

3. Interrupt function Interrupt () there is a lot of talk online that the correct way to terminate a thread is to use a interrupt interrupt, but is that really the case? Practice the truth, wait and see! As mentioned in 2, if a thread has thread.sleep () blocking, changing the identity variable cannot achieve the purpose of terminating the thread, then the Interrupt function interrupt () of the thread class can be used, such as:
public class Testcallable extends Thread {bufferedreader reader = new BufferedReader (new InputStreamReader (system.in))    ;    public void Stopthread () {interrupt (); } public void Run () {try {BufferedReader reader = new BufferedReader (New InputStreamReader (SYSTEM.I            n));            Reader.close ();                while (!isinterrupted ()) {System.out.println ("thread is running ...");            Thread.Sleep (20000);        } System.out.println ("Thread is terminated.");        } catch (IOException e) {e.printstacktrace ();        } catch (Interruptedexception e) {e.printstacktrace ();            }} public static void Main (string[] args) {try {testcallable cal = new testcallable ();            Cal.start ();            Thread.Sleep (2000);            Cal.stopthread (); SYSTEM.OUT.PRINTLN ("The terminated thread command has been released.        ");        } catch (Exception e) {e.printstacktrace (); }    }}
When the thread object's interrupt () is called, the sleep thread throws a Interruptedexception exception, interrupting the loop and terminating the thread. However, if the IO is input to these blocks, the interrupt method does not work, and there is no blocking thread, the call to interrupt () is not up to the end thread effect. So, interrupt () interrupt the thread in which blocking operations can play a role in throwing interruptedexception? Let's do an experiment with the following code:
public class Testcallable {public static void main (string[] args) {//test non-blocking case, interrupt Thread thread1 = NE                    W Thread () {public void run () {try {long time = System.currenttimemillis (); while (System.currenttimemillis ()-time<5000) {} System.out.prin                TLN ("A1");                    } catch (Exception e) {System.out.println ("B1");                System.out.println ("B1:" + e.tostring ());        }            }        };        Thread1.start ();        Thread1.interrupt ();                    Interrupt thread thread2 = new Thread () {public void run () {try {) during thread sleep                    This.sleep (5000);                System.out.println ("A2");                    } catch (Exception e) {System.out.println ("B2");                System.out.println ("B2:" + e.tostring ());   }            }        };     Thread2.start ();        Thread2.interrupt ();                    Interrupt in the thread wait state where wait () is not in the synchronization block Thread thread3 = new Thread () {public void run () {try {                    This.wait (5000);                System.out.println ("A3");                    } catch (Exception e) {System.out.println ("B3");                System.out.println ("B3:" + e.tostring ());        }            }        };        Thread3.start ();        Thread3.interrupt ();                    Interrupt in the thread wait state where wait () is in the synchronization block thread thread4 = new Thread () {public void run () {try {                        Synchronized (this) {this.wait (5000);                System.out.println ("A4");}                    } catch (Exception e) {System.out.println ("B4");                System.out.println ("B4:" + e.tostring ());        }            }        };        Thread4.start ();       Thread4.interrupt (); Interrupt when join is blocked Thread THREAD5 = new Thread () {public void run () {try {                    This.join (5000);                System.out.println ("A5");                    } catch (Exception e) {System.out.println ("B5");                System.out.println ("B5:" + e.tostring ());        }            }        };        Thread5.start ();    Thread5.interrupt (); }}
Output Result:
B2B4B4:java.lang.InterruptedExceptionB3B3:java.lang.IllegalMonitorStateExceptionB5B2: Java.lang.InterruptedException:sleep interruptedB5:java.lang.InterruptedExceptionA1
Result Analysis: Output A1: Indicates that interrupts do not work when there is no blocking. OutputB2:java.lang.InterruptedException:sleep interrupted indicates that the interrupt takes effect when the sleep operation is blocked. output B3:java.lang.IllegalMonitorStateException exceptions caused by non-interrupts, which are wait () usage errors, are not detailed here. But just can see, no matter what unusual, can be broken thread ~The output B4:java.lang.InterruptedException indicates that the interrupt takes effect when the wait operation is blocked. The output B5:java.lang.InterruptedException indicates that the interrupt takes effect when the join operation is blocked.
therefore, for the above blocking of the thread, you can use the interrupted () method in the thread break, should say, interrupted is in the waitting and time_waitting state of the threads useful.
So the question is, what if it's another blocking situation? such as IO blocking, and how to interrupt blocking? In fact, from the above example can be broadly concluded: interrupt blocking can be. Such as:
public class Testcallable implements Runnable {    BufferedReader reader = new BufferedReader (New InputStreamReader ( system.in));    public void Stop () {        try {            reader.close ();        } catch (IOException e) {            e.printstacktrace ()}    } Public    void Run () {        try {            while (true) {                System.out.println ("thread begins execution ...");                String cmd = Reader.readline ();            }        } catch (IOException e) {            System.out.println ("IO exception, thread end. ");            E.printstacktrace ();        }    }    public static void Main (string[] args) {        testcallable callable = new testcallable ();        Thread th = new thread (callable);        Th.start ();        Callable.stop ();    }}
By closing the channel, an exception is thrown to interrupt the blocking, and the purpose of terminating the thread is reached. This is true for network IO as well.
4. Summing up through the above analysis, it is not easy to really end a line threads according to our expectations! However, there are two types of methods for terminating threads: for non-blocking situations: setting flag variables, allowing threads to die naturally, harmony! For a blocking situation: interrupt blocking, by throwing an exception to terminate the thread, seemingly violent, but if we expect the exception, it is also safe! Therefore, the final scenario should be determined by combining the application scenarios of your own programs with the specifics of code writing.         Through the above analysis and summary, I personally think that the better way is: (1) whether there is no blocking situation, with the flag variable to control the thread loop. It is incorrect for someone on the web to replace the flag variable in the following way, because it relies on the interrupt state of the thread, which may cause the thread to terminate without expectation.
public void Run () {while    (! Thread.CurrentThread (). isinterrupted ()) {      ...    }}

(2) A function encapsulates the operation of terminating a thread, which leaks to an external call. (3) for the blocking situation in the thread, using the appropriate interrupt method, such as the watting,time_waitting state of the thread, you can use the interrupted () method, for IO blocking, you can close the IO channel and so on.
public class Testcallable implements Runnable {//Whether it is a blocking condition, use a flag variable to control the thread loop private Boolean running;    BufferedReader reader = new BufferedReader (new InputStreamReader (system.in));                /** * Use a function to encapsulate the terminating thread's operation */public void Stop () {running = false;         /* * Use the appropriate interrupt method for blocking situations that occur in the thread.         * such as thread's waitting,time_waitting state, can use interrupted () * To block IO, can close IO channel and so on.        */try {reader.close ();        } catch (IOException e) {e.printstacktrace ();            }} public void Run () {try {running = true;                while (running) {System.out.println ("thread starts executing ...");            String cmd = Reader.readline (); }} catch (IOException e) {System.out.println ("IO exception, thread end.            ");        E.printstacktrace ();        }} public static void Main (string[] args) {testcallable callable = new testcallable ();       Thread th = new thread (callable); Th.start ();    Callable.stop (); }}

5. Broken thoughts would have just summed up the termination thread, did not expect to pull out the thread state, this will be the next detailed. It's really a "Sea of knowledge", the line with the line. However, the harvest is not small, for the network on all kinds of statements, to test, wrong, and finally come to their own solution. If you have better suggestions, warmly welcome!! Recently the company launched a new system, more chaotic state, snatch comb under the blog, more leisurely ~ ~


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java multithreaded Programming--How to terminate a thread

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.