The use of interrupt in Java

Source: Internet
Author: User
Tags volatile

Usually we have the need to stop a thread. In the Java API, there are stop, suspend and other methods can achieve the purpose, but because these methods in the use of non-security, will bring bad side effects, not recommended to be used. For specific reasons, refer to why is Thread.stop deprecated.

In this article, we will discuss the use of interrupts in Java.

Interrupts in Java have 3 main methods, interrupt (), isinterrupted (), and interrupted ().

    • Interrupt (), which invokes the interrupt () method of another thread in one thread, sends a signal to that thread-the thread break state has been set. As to where that thread goes, it is up to the specific code implementation.
    • Isinterrupted (), which is used to determine the interrupt state of the current thread (TRUE or false).
    • Interrupted () is a thread static method used to resume the interrupt state, with the name starting??。

Next, look at how the code is used.

Interrupt () cannot interrupt a running thread, it can only change the interrupt state.

public class Interruptioninjava implements runnable{public    static void Main (string[] args) throws interruptedexception {        Thread testthread = new Thread (new Interruptioninjava (), "Interruptioninjava");        Start thread        testthread.start ();        Thread.Sleep (+);        Interrupt thread        testthread.interrupt ();        System.out.println ("main End");    }    @Override public    Void Run () {while        (true) {            if (Thread.CurrentThread (). isinterrupted ()) {                System.out.println ("Yes,i am interruted,but I am still Running");            } else{                System.out.println ("not yet Interrupted");}}}    

The results show that after being interrupted, it still runs, printing yes,i am interruted,but I am still running

So, how to interrupt correctly?

Since it is only possible to modify the interrupt state, we should do something about the interrupt state.

public class Interruptioninjava implements runnable{public    static void Main (string[] args) throws interruptedexception {        Thread testthread = new Thread (new Interruptioninjava (), "Interruptioninjava");        Start thread        testthread.start ();//        Thread.Sleep (+);        Interrupt thread        testthread.interrupt ();        System.out.println ("main End");    }    @Override public    Void Run () {while        (true) {            if (Thread.CurrentThread (). isinterrupted ()) {                System.out.println ("Yes,i am interruted,but I am still Running");                return;            } else{                System.out.println ("not yet Interrupted");}}}    

To modify the code, add a return to okay in the state judgment as above. But in reality, we may need to do more general, can not help but issue days to ask, how to break the process? The answer is to add a switch .

public class Interruptioninjava implements runnable{    private volatile static Boolean on = FALSE;    public static void Main (string[] args) throws interruptedexception {        thread testthread = new Thread (New Interruptionin Java (), "Interruptioninjava");        Start thread        testthread.start ();        Thread.Sleep (+);        Interruptioninjava.on = true;        System.out.println ("main End");    }    @Override public    Void Run () {while        (!on) {            if (Thread.CurrentThread (). isinterrupted ()) {                System.out.println ("Yes,i am interruted,but I am still Running");            } else{                System.out.println ("not yet Interrupted");}}}    

Will output a similar result, which indicates a successful break:

This kind of switch seems to be a cure for all ills, but when it comes to thread blocking, it's frustrating, as the following code shows:

public class Interruptioninjava implements runnable{    private volatile static Boolean on = FALSE;    public static void Main (string[] args) throws interruptedexception {        thread testthread = new Thread (New Interruptionin Java (), "Interruptioninjava");        Start thread        testthread.start ();        Thread.Sleep (+);        Interruptioninjava.on = true;        System.out.println ("main End");    }    @Override public    Void Run () {        while (!on) {            try {                thread.sleep (10000000)            } catch (Interruptedexception e) {                System.out.println ("Caught exception:" +e);}}}    

The thread is blocked and cannot be interrupted. At this time the Savior interrupt function is back, it can quickly interrupt the blocked thread, throw a interruptedexception, the thread from the blocking state rescued, show the code.

public class Interruptioninjava implements runnable{    private volatile static Boolean on = FALSE;    public static void Main (string[] args) throws interruptedexception {        thread testthread = new Thread (New Interruptionin Java (), "Interruptioninjava");        Start thread        testthread.start ();        Thread.Sleep (+);        Interruptioninjava.on = true;        Testthread.interrupt ();        System.out.println ("main End");    }    @Override public    Void Run () {        while (!on) {            try {                thread.sleep (10000000)            } catch (Interruptedexception e) {                System.out.println ("Caught Exception right now:" +e);}}}    

As a result, it achieves expectations.

This also applies to IO blocking, which usually throws an socketexception immediately, similar to the interruptedexception described above.

The use of interrupt in Java

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.