Java thread legends (1) -- Use of Interrupt thread interrupted

Source: Internet
Author: User

 Interrupt thread
-- Interrupt ()

Can a running thread be controlled by other threads except for normal time slice interruptions? Or can other threads let the specified Thread discard the CPU or stop running ahead of schedule?
In addition to the thread synchronization mechanism, there are two methods:

(1) methods for terminating thread running, such as thread. Stop (), thread. Suspend (), thread. Resume (), and runtime. runfinalizersonexit. These methods have been discarded and they are extremely insecure.

(2) The thread. Interrupt () method is a good choice. However, when using it, we must understand its usefulness.

// The Running thread code class testrunnable implements runnable {public void run () {While (true) {system. out. println ("thread is running... "); long time = system. currenttimemillis (); // The number of milliseconds for removing the system time while (system. currenttimemillis ()-time <1000) {// The program loops for 1 second. Unlike sleep (1000), the process is blocked. }}} Public class threaddemo {public static void main (string [] ARGs) {runnable r = new testrunnable (); thread Th1 = new thread (r); th1.start (); th1.interrupt () ;}/// running result: Print thread is running once in one second .... The program has no signs of termination

The above Code indicates that interrupt () does not interrupt a running thread, or let a running thread discard the CPU. So what is the interruption of interrupt.

First, let's take a look at what interrupt is doing.

When th1.interrput () is called, the thread's interruption status (interrupted status) is set. We can check the interruption status of this Boolean Type through thread. currentthread (). isinterrupted.

In core Java, there is a saying: "There is no language requirement that an interrupted program should be terminated. A thread is interrupted only to attract the attention of the thread. The interrupted thread can decide how to deal with the interruption ". Let's take a good look at the following code:

// Interrupted's classic code: Public void run () {try {... while (! Thread. currentthread (). isinterrupted () & more work to do) {// do more work;} catch (interruptedexception E) {// thread was interrupted during sleep or wait} finally {// cleanup, if required }}

Obviously, in the above Code, a deciding factor in the while loop is that you need to constantly check your interrupt status. When the External Thread calls the interrupt of this thread
The interrupt status is set. This indicates that the thread will terminate the loop and does not do more work in the execution loop.


This indicates that interrupt interrupts a certain part of the thread's business logic, provided that the thread needs to check its own interrupt status (isinterrupted ()).


However, when TH1 is blocked, for example, when it is blocked by one of three methods: object. Wait, thread. Join, and thread. Sleep. Call its interrput () method. As you can imagine, threads that do not occupy CPU and run cannot set their own interrupt status. This produces an interruptedexception exception.

// Interrupt a blocked thread code class testrunnable implements runnable {public void run () {try {thread. sleep (1000000); // This thread will be blocked for 1000 seconds} catch (interruptedexception e) {e. printstacktrace (); // do more work and return .}}} public class testdemo2 {public static void main (string [] ARGs) {runnable TR = new testrunnable (); thread Th1 = new thread (TR); th1.start (); // start executing the sub-thread while (true) {th1.interrupt (); // interrupt this sub-thread }}/ * running result: Java. lang. interruptedexception: sleep interrupted at java. lang. thread. sleep (native method) at testrunnable. run (testdemo2.java: 4) At java. lang. thread. run (unknown source )*/

*
If a thread is blocked, it cannot check shared variables and stop. This occurs in many cases, such as calling
*
When object. Wait (), serversocket. Accept (), and datagramsocket. Receive (), they may always
*
Long-time blocking thread. Even if a timeout occurs, it is not feasible and inappropriate to wait until the timeout period expires.
*
A mechanism is used to make the thread exit the blocked state earlier. Unfortunately, there is no such mechanism for all situations.
*
But specific technologies can be used according to different situations. Use thread. Interrupt () to interrupt the normal thread
*
As described in example1, the thread. Interrupt () method does not interrupt a running thread. This method
*
What is actually done is to throw an interrupt signal when the thread is blocked, so that the thread can exit the blocking state. More
*
Specifically, if a thread is blocked by one of three methods: object. Wait, thread. Join, and thread. Sleep,
*
It will receive an interrupt exception (interruptedexception) to terminate the blocked status early.

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.