Java Thread Interrupt

Source: Internet
Author: User

Thread Break:

It is dangerous for the thread to be forced to terminate before it ends normally, which can cause unintended consequences.

But sometimes you want a thread to end, or to end some kind of waiting state, what should I do?

Use the wait / notify mechanism or give that thread an interrupt signal, and let it decide for itself what to do?

Interrupted use of the scene:

1. Thread in order to wait for the arrival of some specific resources, call the Thread.Sleep (10000), let yourself wake up after ten seconds, but if these specific conditions come early to inform the thread in the sleep State, "Hey man, No more sleep. "

2. The thread blocks itself by calling the child thread's join method to wait for the child thread to end, but when the child thread runs it finds itself unable to end in a short period of time, so it notifies the main thread and does not wait for the child thread.

In these cases, an interruption is required.

Function of the interrupt:

  

  Thread.Interrupt () method to do.

like A thread calls this method, which modifies the interrupt state of the A thread.

In a non-blocking thread

This method modifies the interrupt state simply by changing the value of a Boolean variable in the thread, which is called in the process Body run () method . Thread.currendthread (). Isinterrupt () This method returns a true.

In a thread that can unblock the state, such as the thread run () method, call thread.sleep (),thread.join (), object.wait () The threads of these methods are in the process of waiting. This thread calls the interrupt () method, and then the thread.currendthread (). Isinterrupt ( ) value of this thread changes to true. After the thread receives the interrupt signal, it throws a interruptedexception exception.

In a non-blocking state thread:
public class Interrupt {public    static void Main (string[] args) {       //Interrupt interrupt=new Interrupt ();        THREADC threadc=new THREADC ();        Threadc.start ();        try {            thread.sleep;        } catch (Interruptedexception e) {            e.printstacktrace ();        }        Threadc.interrupt ();    }} Class THREADC extends thread{public    void Run () {while        (true) {            if (Thread.CurrentThread (). Isinterrupted ()) {                System.out.println ("Someone Interrupt Me");            } else{                System.out.println ("Thread is going ...");}}            }    
Operation Result:

Results Analysis:

The main method threadc begins execution, and theTHREADC thread is not interrupted at this time, continuously outputting thread is going.

after the main thread sleeps for 3 seconds , the threadc.interrupt () method is executed and the interrupt thread is The value of Thread.CurrentThread (). isinterrupted () becomes true. But the thread does not stop, it will constantly output Someone interrupt me, it is only modified by an interrupt signal.

when the threadc.interrupt () method is called in the main method , the interrupt state of the thread threadc ( Interrupted status ) is set and then passed through Thread.CurrentThread () in the thread body . isinterrupted () To check the interrupt state of this Boolean variable.

threads that are blocking state:

public class Interrupt {public    static void  threadd threadd=new threadd ();        Threadd.start ();        SYSTEM.OUT.PRINTLN ("Thread Start Execution");        try {            thread.sleep;        } catch (Interruptedexception e) {            e.printstacktrace ();        }        System.out.println ("Break Thread");        Threadd.interrupt ();    }} Class Threadd extends thread{    boolean  stop=false;    public void Run () {//        while (!stop) {//            System.out.println ("Thread is going ...");//        }        try {            Thread.Sleep (+);        } catch (Interruptedexception e) {            System.out.println ("Thread Sleep Interrupted");        }        SYSTEM.OUT.PRINTLN ("Thread continues execution ...");}    } Main (string[] args) {

Operation Result:

Results Analysis:

if the thread is The Object.warit (),thread.sleep (),thread.join () methods block, calling the thread's The interrupt () method throws an interruptexception exception, thus ending the blocking state early.

Thread Sleep 3 seconds,main method sleep 2 seconds after executing threadd.interrupt () method. At this point the thread throws an exception and ends the sleep.

Other:

not all blocking methods can be unblocked after they receive an interrupt, and the input and output classes block waiting IO is complete, but they do not throw interruptedexception, and they do not exit the blocking state when they are interrupted.

Synchronized cannot be interrupted in the process of being locked.

but the Reentrantlock supports an interruptible fetch mode, which is Trylock (long time, timeunit unit).

Java Thread Interrupt

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.