Multithreading---stop threads

Source: Internet
Author: User
Tags thread stop

Stop threads are not as Break,return in the Java language as they are, and require some skill.

The thread's stop was thought to be simple, a interupt () method was done, and in fact it was completely wrong, and the thread's Stop API did provide a simple way to stop (), but it was already tagged out of date in the new API because he was not safe enough.
In Java, 2 methods are provided to terminate a running thread:
1 use Exit flag, so that the thread to exit normally, that is, run () completed after the thread terminated
2 use stop to force termination of the thread, but not recommended, produce unpredictable consequences
3 using interrupt to terminate the thread interrupt () does not stop the thread
Maybe I said, you do not believe, then a demo to verify the

public class A extends Thread {
    @Override public
    void Run () {for
        (int j=0;j<50000;j++)
            { System.out.println ("j=" +j);


}} public static void Main (string[] args) {
        A A = new A ();
        A.start ();
        try {
            thread.sleep ();
            A.interrupt ();
        } catch (Interruptedexception e) {
            e.printstacktrace ();
            System.out.println (E.tostring ());
        }

    

Look at the print results:

No less printing, which means that interrupt () does not stop the thread, the call to interrupt () is only a stop tag in the current thread, not really stop the thread. correctly determine the running state of a thread
To properly stop a thread, you must know what time the thread is in its lifecycle, and you must understand these APIs.
1) interrupted ();
2) isinterrupted ();

Let's take a look at these 2 introductions:

This is very clear, interrupted () test when the line is interrupted, and clear the interrupt state, isinterrupted () is the test thread has been interrupted, does not affect the state of the thread;
Here is a demo to explain:

    public static void Main (string[] args) {
        A A = new A ();
        A.start ();
        try {
            thread.sleep ();
            A.interrupt ();
            System.out.println ("Interrupted:" +a.interrupted ());
            System.out.println ("Interrupted:" +a.interrupted ());
            System.out.println ("is interrupted:" +a.isinterrupted ());
            System.out.println ("is interrupted:" +a.isinterrupted ());

        } catch (Interruptedexception e) {
            e.printstacktrace ();
            System.out.println (E.tostring ());
        }

    

Print results

To modify:

public static void Main (string[] args) {
        A A = new A ();
        A.start ();
        try {
            thread.sleep ();
            A.interrupt ();
            Thread.CurrentThread (). interrupt ();
            System.out.println ("Interrupted:" +thread.interrupted ());
            System.out.println ("Interrupted:" +thread.interrupted ());
            System.out.println ("is interrupted:" +a.isinterrupted ());
            System.out.println ("is interrupted:" +a.isinterrupted ());

        } catch (Interruptedexception e) {
            e.printstacktrace ();
            System.out.println (E.tostring ());
        }

    

Look at the print again:

This result confirms the API's description of interrupted (), which tests the status of the thread and clears the interrupt state.

Analysis: First look at the first case, only the implementation of the A.interrupt (), although the implementation of the a.interrupted (), but still detect the current thread, the main thread (main) has not been interrupted, so the first time of the Interrupted=false;
In the second case: Thread.currentThread.interrupt () interrupts the main thread, so the first time interrupted=true, because he also has a role to clear the current thread interrupt state, so the second time interrupted= False

In a change, look at the isinterrupted

public class A extends Thread {
    @Override public
    void Run () {for
        (int j=0;j<500000;j++)
            { System.out.println ("j=" +j);
            if (this.isinterrupted ()) {
                System.out.println ("is interrupted:" +this.isinterrupted ());
                System.out.println ("is interrupted:" +this.isinterrupted ());
                Break

;

}}} public static void Main (string[] args) {
        A A = new A ();
        A.start ();
        try {
            thread.sleep ();
            A.interrupt ();
        } catch (Interruptedexception e) {
            e.printstacktrace ();
            System.out.println (E.tostring ());
        }

    

Look at the print results:

See here that isinterrupted () does not clear the end of the thread, so the 2 times will be true, although the state is ture, just jump out of the loop, but the thread will still run. Exception method Stop thread
With the previous API for detecting thread State, you can provide a basis for stopping the thread

public class A extends Thread {
    @Override public
    void Run () {
        try{for
            (int j=0;j<500000;j++)
                { System.out.println ("j=" +j);
                if (this.isinterrupted ()) {
                    throw new Interruptedexception ("Thread is Interrupted");
                }
            System.out.println ("For After Run");
            Do some
        }catch (Exception e) {
            System.out.println (e.tostring ());

}}} public static void Main (string[] args) {
        try {
            A A = new A ();
            A.start ();
            Thread.Sleep (1000);
            A.interrupt ();

        } catch (Interruptedexception e) {
            e.printstacktrace ();
            System.out.println (E.tostring ());
        }

    

Look at the print results

The thread did stop and the for statement was not executed

Return Stop Thread
The throw new Interruptedexception ("Thread is Interrupted") in the above code is changed to return or the thread terminates, but it is best to use the exception method, because the exception in the catch block can be thrown up. Causes thread stop events to propagate

use the Stop Stop thread (not recommended)
Take a look at the adverse consequences of the use,

public class Synobject {private String name= "a";

    Private String pwd= "AAA";
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public String getpwd () {return pwd;
    } public void SetPwd (String pwd) {this.pwd = pwd;
            } synchronized public void printstring (String name,string pwd) {try {this.name = name;
            Thread.Sleep (100*1000);
        This.pwd = pwd;
        catch (Interruptedexception e) {e.printstacktrace ();

    }} public class A extends Thread {private Synobject object;
    Public A (Synobject object) {This.object = object;
    @Override public void Run () {object.printstring ("B", "BBB");
            } public static void Main (string[] args) throws Exception {Synobject object = new Synobject ();
            A A = new A (object);
    A.start ();        Thread.Sleep (500);
            A.stop ();
    System.out.println ("Name:" +object.getname () + ", pwd:" +object.getpwd ()); }

This logic is simple, the object attribute is initialized, printstring the property, and look at the result

Although the thread was stopped in time, the results obtained were not what we expected. Stop () forcibly stopped, may make some cleanup work is not completed, resulting in memory leakage; the other is to lock the object to "unlock", resulting in data is not synchronized, the problem of inconsistent data; so it's best not to use B.

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.