Java Concurrency: Thread interrupt-interrupt

Source: Internet
Author: User

Always thought that executing the interrupt method would allow the thread to end and throw interruptedexception. Read the Java concurrency Programming today in the seventh chapter of the discovery is not so, in the beginning of this chapter mentioned

It's not easy to get tasks and threads to stop safely, quickly, and reliably. Java does not provide any mechanism to safely terminate a thread. But it provides (interruption), which is a collaborative mechanism that enables one thread to terminate the current work of another thread

As mentioned above is collaboration , not coercion. Because if a thread task implementation that needs to be interrupted is not subject to such a collaboration contract, then no other thread will be able to break it through the interrupt. For example, the following foreverthread does not detect the Boolean variable set by the interrupt.

Thread Foreverthread =NewThread (NewRunnable () {@Override Public voidrun () {intt =0;  for(inti =0; I <1; i++) {i--; if(t++%10000==0) {System. out. println (".");        }                }            }        });        Foreverthread.start (); Foreverthread.interrupt ();

As described in the book, each thread has a Boolean interrupt state, and we can set this value to True by calling the thread's interrupt method, and the Isinterrupted method is used to detect whether the value is reset to True. So when a thread (such as the main thread) interrupt the method by invoking another (such as a task) thread, then the task thread has the logic to detect if the Boolean value is set, and if true this aborts the current work, A interruptexception is then thrown as a library method to prompt that the current task execution is interrupted. Because interrupt sets this Boolean variable to be thread-body dependent, it will always exist in the thread body once set, so if you do not reset it to false, subsequent operations that will detect the variable will immediately exit the throw interruptexception. For this reason, when the Boolean token is detected to be set to true, before the interruptexception is thrown, it is also called by calling Thread.interrupted () method to reset the Boolean token (that is, set to false) in order to avoid affecting subsequent operations (this also means that the part of the code that performs this action deals with the interrupt request, which is generally referred to as the above-thrown interruptexception).

Blocking library methods, such as Thread.Sleep and object.wait, detect when a thread is interrupted and return early when an outage is found. The actions they perform in response to an outage include clearing the interrupt state, throwing a interruptexception, indicating that the blocking operation ended prematurely due to an outage.

The interrupt method of the thread instance is used to set the Boolean token, and the static Thread.interrupted method is used to clear the Boolean token (that is, false, while returning the previous Boolean value) below is an instance:

        Thread Ithread = thread.currentthread ();        Ithread.interrupt ();        System.  out . println (ithread.isinterrupted ());        System.  out . println (thread.interrupted ());        System. out. println (ithread.isinterrupted ());

The output is as follows:

true true false

Use caution when using static interrupted because it clears the interrupt state of the current thread. If you return True when you call interrupted, you must handle the interrupt unless you want to block it--you can throw interruptedexception, or resume the interrupt by calling interrupt again.

If we throw an exception after detecting a interrupt interrupt and do not call the interrupted clear tag, then other interruptible calls will be affected later:

        New Linkedblockingqueue<integer>();         = Thread.CurrentThread ();        Ithread.interrupt ();        System.out.println (ithread.isinterrupted ());         Try {            queue.take ();         Catch (interruptedexception e) {            System.out.println ("Thread is interrupted, isinterrupted:" +  Ithread.isinterrupted ());        }

Output:

true thread is interrupted, isinterrupted: false

Run the code snippet above and the program will end immediately without waiting on Queue.take (). After the library function throws Interruptexception, the interrupt Boolean token has been cleared (false) by isinterrupted detection

Java Concurrency: Thread interrupt-interrupt

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.