(4) Java thread interrupt 2

Source: Internet
Author: User

It is dangerous for a thread to be forced to terminate before it ends normally. Because it can bring serious consequences that are completely unforeseen. So you see Thread.Suspend, Thread.stop and other methods have been deprecated.
So you can't just hang a thread out of it, but sometimes it's necessary to let a thread die or let it end a waiting state. The elegant approach is to give that thread an interrupt signal and let it decide for itself what to do. For example, in a child thread to wait for certain conditions to arrive, you call Thread.Sleep (10000), expect the thread to wake up after 10 seconds of sleep, but if this particular condition arrives early, how do you inform a sleeping thread? For example, the main thread blocks itself by calling the join method of the child thread to wait for the child thread to end, but the child thread finds itself in a short period of time to end, so it needs to find a way to tell the main line Cheng wait for me. In these cases, an interruption is required.
Interrupts are done by calling the Thread.Interrupt () method. This method informs that thread by modifying the interrupt state of the called thread, saying that it was interrupted. For non-blocking threads, only the interrupt state is changed, that is, thread.isinterrupted () will return true; For threads in the unblocking state that can be canceled, such as a thread waiting on these functions, Thread.Sleep (), object.wait (), Thread.Join (), this thread will throw interruptedexception after receiving the interrupt signal, It also resets the interrupt state back to false.
The following program demonstrates interrupts to non-blocking threads:

 Public classThread3extendsthread{ Public voidrun () { while(true){              if(thread.interrupted ()) {System.out.println ("Someone interrupted me."); }              Else{System.out.println ("Going ..."); }              Longnow =System.currenttimemillis ();  while(System.currenttimemillis ()-now<1000){                  //to avoid thread.sleep () and the need to capture interruptedexception and the confusion of understanding,//1 seconds of idling in this way here .            }          }      }             Public Static voidMain (string[] args)throwsinterruptedexception {Thread3 T=NewThread3 ();          T.start (); Thread.Sleep (3000);      T.interrupt (); }  }  

The following program demonstrates that the child thread notifies the parent line Cheng to wait for it:

 Public classThread4extendsThread {PrivateThread Parent;  PublicThread4 (Thread parent) { This. Parent =parent; }             Public voidrun () { while(true) {System.out.println ("Sub thread is running ..."); Longnow =System.currenttimemillis ();  while(System.currenttimemillis ()-Now < 2000) {                  //to avoid thread.sleep () and the need to capture interruptedexception and the confusion of understanding,//2 seconds of idling in this way here .} parent.interrupt (); }      }             Public Static voidMain (string[] args) {Thread4 T=NewThread4 (Thread.CurrentThread ());          T.start (); Try{t.join (); } Catch(interruptedexception e) {System.out.println ("Parent thread would die ..."); }      }  }  

The interrupt state can be read by thread.isinterrupted () and can be read and purged by a static method called thread.interrupted () (that is, after the method is called, the break state becomes false).
Because the blocked thread throws exception and resets the interrupt state after it is interrupted, it is sometimes disadvantageous because the interrupt state may be used as a criterion for other threads, so it is prudent to reset the state at the point where the exception is handled:

Booleaninterrupted =false; Try {       while(true) {          Try {              returnBlockingqueue.take (); } Catch(Interruptedexception e) {interrupted=true; }      }  } finally {      if(interrupted) {Thread.CurrentThread (). interrupt (); }  }  

When you need to throw a interruptedexception in the code call, you can choose to reset the interrupt state, or you can choose to throw the interruptedexception out, which is determined by the caller of the outer layer.

Not all blocking methods can be unblocked after receiving an interrupt, and the input and output stream classes block waiting for I/O completion, but they do not throw interruptedexception and do not exit the blocking state without being interrupted.

An attempt to acquire an internal lock (into a synchronized block) cannot be interrupted, but the Reentrantlock supports an interruptible fetch mode of trylock (long time, Timeunit unit).

(4) Java thread interrupt 2

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.