Java basic Knowledge Review Java Thread class learning (12)-Thread break

Source: Internet
Author: User

Official Document Translation:

If this thread is in a blocked state: The calling thread's wait (), wait (long) or wait (long, int) will let it enter the waiting (blocking) state, or the calling thread's join (), join (long),

Join (long, int), sleep (long), and sleep (long, int) will also let it go into a blocking state. If the thread is in a blocking state, its interrupt () method is called, then

Its "interrupt state" is cleared and a Interruptedexception exception is received. For example, a thread enters a blocking state through wait (), at which point the thread is interrupted by interrupt ();

Calling interrupt () immediately sets the interrupt token of the thread to "true", but because the thread is blocked, the break token is immediately cleared to "false" and a Interruptedexception exception is generated.

If the thread is blocked in a selector selector, it is interrupted by interrupt (), the thread's interrupt token is set to true, and it is immediately returned from the selection operation.

If this is not the case, the interrupt token is set to "true" when the thread is broken through interrupt (). interrupting a "terminated thread" does not result in any action.

The threads are terminated in "blocking state" and "running state" in the following ways:

(1) Use isinterrupted to judge, use interrupt interrupt

@Override  Public void run () {    try  {        //  1. isinterrupted () guarantees that the thread is terminated as long as the interrupt is marked as true. while         (!  Isinterrupted ()) {            //  perform task ...         }    catch  (Interruptedexception IE) {          //  2. The interruptedexception exception guarantees that the thread is terminated when the interruptedexception exception is generated.     }}

Example 1:

 Packageconcurrentmy.interrupts;/*** * (interrupt () is often used to terminate the "blocking state" thread.             * * <p> * Revision history: <br> * Modified Date Modified by staff version        Modified Content <br> *-------------------------------------------------<br> * November 3, 2016 2:56:44 User 1.0 Initialize Create <br> * </p> * *@authorPeng.li *@version1.0 *@sinceJDK1.7 * Run Result: the status of a thread: (NEW) is the state of the Newa thread: (RUNNABLE) is the status of the Starta thread: (RUNNABLE) loop 1A thread Status: (RUNNABLE) loop 2 A thread state: (timed_waiting) is the state of the thread: (RUNNABLE) The state of the Catch Interruptedexception.a Thread: (TERMINATED) is        Interrupted now results Note: 1. The main thread creates thread T1 through new threadmy ("A") and then starts thread A by T1.start (). 2. After thread A starts, it constantly checks its interrupt ID, and if the interrupt is identified as false, after hibernation 100ms 3.t1 hibernation, it switches to the main thread main, the main thread runs again, executes T1.interrupt (), interrupts the A thread, and a receives the interrupt instruction. Sets the interrupt identity of the A thread to "false" and throws an Interruptedexception exception **/classThreadmyextendsThread { Publicthreadmy (String name) {Super(name); } @Override Public voidrun () {inti = 0; Try {            //1. isinterrupted () guarantees that the thread is terminated as long as the interrupt is marked as true.              while(!isinterrupted ()) {                //thread A sleeps, enters blocking stateThread.Sleep (100); I++; //returns the status of the current threadSystem.out.println (Thread.CurrentThread (). GetName () + "Thread Status: (" + This. GetState () + ") loop" +i); }                    } Catch(interruptedexception e) {//2. Interruptedexception exception guarantees that the thread is terminated when the interruptedexception exception is generated. //Todo:handle ExceptionSystem.out.println (Thread.CurrentThread (). GetName () + "Thread Status: (" + This. GetState () + ") Catch interruptedexception."); }    }} Public classDemo1_interrupt { Public Static voidMain (string[] args) {Try {            //New Thread Athreadmy T1 =NewThreadmy ("A"); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is new"); //start thread AT1.start (); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is start"); //The main thread sleeps for 300 milliseconds, and then main threads send instructions to T1Thread.Sleep (300);                        T1.interrupt (); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is interrupted"); //The main thread then sleeps 300ms, looking at the status of a threadsThread.Sleep (300); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is interrupted now"); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

(2) A secure terminating thread that uses a volatile Boolean variable.

 Packageconcurrentmy.interrupts;/*** * * <p> * Revision history: <br> * Modified Date Modified by staff version     What's changed <br> *-------------------------------------------------<br> * November 3, 2016 PM 2:56:44 user 1.0 Initialization Creation <br> * </p> * *@authorPeng.li *@version1.0 *@sinceJDK1.7 * Secure terminating thread, using volatile Boolean variables. Run result: The status of a thread: (NEW) is Newa the state of the thread: (RUNNABLE) is the state of the thread: (RUNNABLE) The status of the Loop 1A thread: (RUNNABLE) loop 2A status of the thread: (Timed_waiti NG) is the state of the Interrupteda thread: (RUNNABLE) loop 3count3a The status of the thread: (TERMINATED) is interrupted now results description: 1. The main thread is created by new Threadmy ("A")        Build thread T1, and then start thread A by T1.start (). 2. After thread A starts, it constantly checks its interrupt ID, if the interrupt is identified as true, then hibernate 100ms 3.t1 hibernate, it will switch to main thread main, the main thread will run again, execute T1.cancel (), interrupt a thread, a after receiving the interrupt instruction, a thread The interrupt ID is set to "false", the interrupt ID is cleared, and the interruptedexception exception is thrown * * **/classThreadMy1extendsThread {//volatile application, to ensure that the visibility of the on identity between threads, a thread (main thread) changed the identity,//that is, calling the Cancel method of the a thread cancels or stops the task (the execution of a thread is immediately visible to the thread (a thread)    Private volatile BooleanOn =true;  PublicThreadMy1 (String name) {Super(name); }    /*** * (//through the on variable to control whether you need to stop the task and terminate the task) **/     Public voidCancel () { on=false; } @Override Public voidrun () {inti = 0; Try {            //on = False when interrupt thread             while(On/*&&!isinterrupted ()*/) {                //thread A sleeps, enters blocking stateThread.Sleep (100); I++; //returns the status of the current threadSystem.out.println (Thread.CurrentThread (). GetName () + "Thread Status: (" + This. GetState () + ") loop" +i); } System.out.println ("Count" +i); } Catch(interruptedexception e) {//2. Interruptedexception exception Guarantee, when the interruptedexception exception is generated, the thread is terminated, this place adds some log operations//Todo:handle ExceptionSystem.out.println (Thread.CurrentThread (). GetName () + "Thread Status: (" + This. GetState () + ") Catch interruptedexception."); }    }} Public classDemo2_interrupt { Public Static voidMain (string[] args) {Try {            //New Thread AThreadMy1 T1 =NewThreadMy1 ("A"); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is new"); //start thread AT1.start (); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is start"); //The main thread sleeps for 300 milliseconds, and then main threads send instructions to T1Thread.Sleep (300); //break thread inT1.cancel (); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is interrupted"); //The main thread then sleeps 300ms, looking at the status of a threadsThread.Sleep (300); System.out.println (T1.getname ()+ "Thread Status: (" + t1.getstate () + ") is interrupted now"); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Java basic Knowledge Review Java Thread class learning (12)-Thread break

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.