Java Interrupt Little Note

Source: Internet
Author: User

There are three interrupt-related functions in Java:
1. Set the interrupt state to true by using the member method Thread.interrupt ()
2. Thread by member method . is InterrupTed () to get the interrupt status
3. The static method thread.interrupted () to get the interrupt state, and clear the interrupt state (of course to get the value of the previous purge), that is
, two times in a row to call this method, The second time will definitely return false.

Each method is described in more detail below.

    1. Member Method New Thread (). Interrupt ()

The member method of the thread is new thread (). Interrupt () is a thread that sets the interrupt state bit for the threads, which is set to True (False by default), whether the resulting thread is dead, waiting for a new task, or continues to the next step. It depends on the program itself. The thread will detect the interrupt from time to times

Flag to determine if the thread should be interrupted (the interrupt flag value is true). It is not like a Stop method (which rarely ends a thread with stop, uses a shared variable or another method to implement the end of a thread), and interrupts a running thread.

However, the interrupt () method does not interrupt a thread that is running (refer to the http://yimaoqian.blog.51cto.com/1328422/1399767 blog post for thread status), and the program instance is as follows:

Public class testsun {    public static void main (String[]  args) {        // test1         thread t1 = new thread () {              @Override              Public void run () {                 try{                     int i=0;                     while (i++<100000000) {                          // nothing                     }                     system.out.println ("A1");                 }catch (exception e) {                     system.out.println ("B1");             };        };         t1.start ();              system.out.println (t1.isinterrupted ()  +  " before");// See if the thread is interrupted (interrupt flag bit)         t1.interrupt ();//Do not interrupt running thread          system.out. println (t1.isinterrupted ()  +  " after");     }}----------------------------- -------------------------------Running Result: false beforetrue aftera1

T1.interrupt () is analyzed by the running results without interrupting the thread T1, which means that the interrupt () method of the member method does not work on the running method (that is, no blocking), only the thread that is in the blocking function .

Interrupt () method interrupts are in a blocking state (where the blocking state does not include a thread that is caused by an IO operation, including only wait, join, sleep), the interruptedexception exception is thrown, and the The interrupt state is cleared (the True purge, which is set when the interrupt () method is called, becomes false). Program Examples:

Public class testsun {    public static void main (String[]  args) {        // test1         thread t1 = new thread () {              @Override              Public void run () {                 try{                     int i=0;                     while (i++<100000000) {                          // nothing                     }                     system.out.println ("A1");                     thread.sleep (5000);//Blocking thread                  }catch (exception e) {                      System.out.println ("B1");                     //break flag after throwing exception                      system.out.println (Thread.currentThread (). isinterrupted ()  +  "  In catch ");                                      }            };         };        t1.start ();                system.out.println ( t1.isinterrupted ()  +  " before");         t1.interrupt () ;//Do not interrupt the running thread         system.out.println (t1.isinterrupted ()  +   " after");     }}--------------------------------------------running results:false  Beforetrue aftera1b1false in catch

    says that the interrupt () method cannot interrupt a blocked thread due to an IO operation, as described here under a program:

import java.io.ioexception;import java.net.serversocket;import java.net.socket;public  Class exemple4 extends thread {      public static  void main ( String args[] )  throws Exception {             exemple4 thread = new exemple4 ();            system.out.println (  "Starting thread ..."  )            thread.start ();            thread.sleep ( 3000 );            system.out.println (  "Interrupting thread ..."  );            thread.interrupt ();           &nbSp Thread.Sleep ( 3000 );            System.out.println (  "stopping application ..."  );           }          public void run ()  {           ServerSocket socket;             try {               socket = new serversocket (7856);             } catch  ( IOException e )  {             system.out.println (  "Could not create the socket ..."  );               return;            }             while  ( true )  {              system.out.println (  "Waiting for connection ..."  );              try {                socket sock =  socket.accept ();               }  catch  ( IOException e )  {               system.out.println (  "accept ()  failed or interrupted ..."  );              }             }          }}------------------- ------------------------running results: Starting thread ... Waiting for connection ... Interrupting thread ... Stopping application ...

The

Interrupt () method does not yet break the thread of the deadlock state because the locked position cannot throw an exception at all. Program Example:

Public class exemple4 extends thread {    public static  void main (string args[])  throws Exception {         final object lock1 = new object ();         final object lock2 = new object ();         thread thread1 = new thread ()  {             public void run ()  {                 deathlock (Lock1, lock2);             }        };         thread thread2 = new thread ()  {        &nbSp;    public void run ()  {                 //  Note that this place is in exchange for a bit                  deathlock (LOCK2,&NBSP;LOCK1);             }        };         system.out.println ("Starting thread ...");         thread1.start ();         Thread2.start ();         thread.sleep (;    )     system.out.println ("Interrupting thread ...");         thread1.interrupt ();         thread2.interrupt ();         thrEad.sleep (&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN); ("Stopping application ... ");     }    static void deathlock (Object lock1, &NBSP;OBJECT&NBSP;LOCK2)  {        try {             synchronized  (LOCK1)  {                 thread.sleep (Ten);//  won't die here                 // system.out.println (lock1 +  " thread ...");                 synchronized  (LOCK2)  {//  will be locked here, although blocked, but will not throw exceptions                       System.out.println (Thread.currentthreAD ());                }             }         } catch  (interruptedexception e)  {             system.out.println ("Exception thread ...");             e.printstacktrace ();             system.exit (1);         }    }      -----------------------------------------------------  Operation result:starting  Thread ... Interrupting thread ... Stopping application ...

     the thread can break gracefully when no deadlock occurs, the program instance:

        thread t4 = new thread () {             public void run () {                 try{                     synchronized ( This) {                         this.wait (50000);                     }                     system.out.println ("A4");                 }catch ( Exception e) {&NBSP;&NBSP;&NBSP;&Nbsp;                 System.out.println ("B4");                 }            };         };        t4.start ();         t4.interrupt ();     //can be interrupted because there's no competition. Lock                  ----------------------------          Operation Result: &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;B4

2. Member method new Thread (). isinterrupted ()




To lights out, first write here, there is time to continue ....


This article is from the "Punk" blog, please be sure to keep this source http://yimaoqian.blog.51cto.com/1328422/1544963

Java Interrupt Little Note

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.