How to interrupt a Java thread

Source: Internet
Author: User
Tags volatile

Some thoughtless fellow may be thread.interrupt by another method. Although its name seems to imply something, however, this approach does not break a running thread (which will be further explained later), as described in Listing a. It creates a thread and tries to stop the thread using the Thread.Interrupt method. The invocation of the Thread.Sleep () method provides ample time for the initialization and abort of the thread. The thread itself does not participate in any useful operations.

class example1 extends thread {             boolean stop=false;             public static void main ( String args[] )  throws exception {             example1 thread = new  example1 ();             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 ..."  );             //system.exit (0);             }             public void run ()  {             while (!stop) {             System.out.println (  "thread is running ..."  );             long time = system.currenttimemillis ();             while ((System.currenttimemillis ()-time < 1000))  {            }             }            system.out.println ( "Thread exiting under request ..."  );             }            }

If you run the code in listing A, you will see the following output in the console:

Starting thread ...

Thread is running ...

Thread is running ...

Thread is running ...

Interrupting thread ...

Thread is running ...

Thread is running ...

Thread is running ...

Stopping application ...

Thread is running ...

Thread is running ...

Thread is running ...
...............................
Even after Thread.Interrupt () is called, the thread continues to run.

to really break a thread

The most recommended way to interrupt a thread is to use a shared variable (GKFX variable) to signal that it must stop a running task. A thread must periodically check this variable (especially during a redundant operation) and then abort the task in an orderly manner. Listing B describes this approach.

Listing bclass example2 extends thread {  volatile boolean stop  = false;  public static void main ( String args[] )   Throws exception {    example2 thread = new example2 ();    system.out.println (  "Starting thread ..."  );    thread.start ();    thread.sleep ( 3000 );    system.out.println (  "asking  Thread to stop ... " );   thread.stop = true;    Thread.Sleep ( 3000 )    system.out.println (  "Stopping application ..."   );    //system.exit ( 0 );   }  public void run ()  {     while  ( !stop )  {     system.out.println (   "Thread is running ..." )       long time = system.currenttimemillis ();       while  (  (System.currenttimemillis ()-time < 1000)   &&  (!stop)  )  {      }    }    system.out.println (  "Thread exiting under request ..."  );   }}


Running the code in Listing B produces the following output (note how the thread exits in an orderly manner)

Starting thread ...

Thread is running ...

Thread is running ...

Thread is running ...

Asking thread to stop ...

Thread exiting under request ...

Stopping application ...

Although this method requires some coding, it is not difficult to implement. At the same time, it gives threads the opportunity to do the necessary cleanup work, which is absolutely necessary in any multithreaded application. Make sure that the shared variable is defined as a volatile type or that all access to it is marshaled into the synchronized block/method (synchronized Blocks/methods).

So far everything goes well! But what happens when a thread waits for some event to occur and is blocked? Of course, if a thread is blocked, it cannot check for shared variables and cannot stop. This can happen in many cases, such as when calling Object.wait (), serversocket.accept (), and datagramsocket.receive (), just a few.

They are all likely to block threads permanently. Even if a timeout occurs, it is not feasible and inappropriate to wait until the timeout expires, so a mechanism is used to allow the thread to exit the blocked state earlier.

Unfortunately, there is no such mechanism applies to all situations, but specific techniques can be used depending on the situation. In the following sections, I will answer the most common examples.

Use Thread.Interrupt () to break the thread

As described in Listing A, the Thread.Interrupt () method does not break a running thread. This approach is actually done by throwing an interrupt signal when the thread is blocked, so that the threads can exit the blocked state. Rather, if the thread is blocked by one of the three methods of Object.wait, Thread.Join, and Thread.Sleep, it will receive an interrupt exception (interruptedexception), thus terminating the blocked state early.

Therefore, if a thread is blocked by several of these methods, the correct way to stop the thread is to set the shared variable and call interrupt () (note that the variable should be set first).if the thread is not blocked, calling interrupt () will not work, otherwise the thread will get an exception (the thread must be prepared to handle the condition beforehand) and then flee the blocking state. In either case, the last thread checks the shared variable and then stops. Listing C This example describes the technique.

Listing cclass example3 extends thread {  volatile boolean stop  = false;  public static void main ( String args[] )   Throws exception {   example3 thread = new example3 ();    system.out.println (  "Starting thread ..."  );    thread.start ();    thread.sleep ( 3000 );    system.out.println (  "Asking thread  to stop " )    thread.stop = true;//if the thread is blocked, this variable will not be checked     thread.interrupt ();    thread.sleep ( 3000 );    system.out.println (  "Stopping application ..."  );    //system.exit ( 0 );   }   public void run ()  {    while  ( !stop )  {      system.oUt.println (  "thread running ..."  );      try {       thread.sleep ( 1000 );      } catch  (  InterruptedException e )  {      system.out.println (  " Thread interrupted ... " );      }    }    system.out.println (  "Thread exiting under request ..."  );   }}

Once Thread.Interrupt () in Listing C is called, the thread receives an exception and then escapes the blocking state and determines that it should stop. Running the above code will get the following output:

Starting thread ...

Thread running ...

Thread running ...

Thread running ...

Asking thread to stop ...

Thread interrupted ...

Thread exiting under request ...

Stopping application ...


Interrupt I/O operations
However, what happens if a thread is blocked while I/O operations are in progress? I/O operations can block threads for a considerable amount of time, especially when it comes to network applications. For example, the server may need to wait for a request, or a network application may have to wait for the remote host to respond.

If you are using a channel (channels) (This is the new I/O API introduced in Java 1.4), then the blocked thread will receive a Closedbyinterruptexception exception. If this is the case, the logic of the code is the same as in the third example, except for the exception.

However, you may be using traditional I/O that existed prior to Java1.0 and require more work. In this case, Thread.Interrupt () will not work because the thread will not exit the blocked state. Listing D describes this behavior. Even though interrupt () is called, the thread does not exit the blocked state

Listing dimport java.io.*;class example4 extends thread {  public  static void main ( String args[] )  throws Exception {     example4 thread = new example4 ();    system.out.println (  " Starting thread " );    thread.start ();    thread.sleep ( 3000  )    system.out.println (  "Interrupting thread ..."  );    Thread.Interrupt ();    thread.sleep ( 3000 );    system.out.println (   "Stopping application"  )    //system.exit ( 0 );  }   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 ..."  );       }    }  }}


    Fortunately, the Java platform provides a solution for this scenario, which is to call the close () method of the socket that blocks the thread. In this case, if the thread is blocked by an I/O operation, the thread will receive a SocketException exception, which is very similar to throwing a interruptedexception exception by using the interrupt () method.

The only thing to note is that a reference to the socket (reference) must exist so that the close () method can be called. This means that the socket object must be shared. Listing e describes the situation. The run logic is the same as the previous example.

listing eimport java.net.*;import java.io.*;class example5 extends thread {   volatile boolean stop = false;  volatile ServerSocket  Socket;  public static void main ( String args[] )  throws  Exception {    example5 thread = new example5 ();    system.out.println (  "Starting thread ..."  );    thread.start ();    thread.sleep ( 3000 );    system.out.println (  "Asking thread to  stop " );    thread.stop = true;   thread.socket.close ();    thread.sleep ( 3000 );    system.out.println (  "stopping  Application " )    //system.exit ( 0 );  }  public  Void run ()  {     try {      socket = new serversocket (7856);     } catch  ( IOException e )  {      system.out.println (  "Could not create the socket ..."  );       return;    }    while  ( !stop )   {     system.out.println (  waiting for connection ... " );       try {       socket sock =  socket.accept ();      } catch  ( IOException e )  {      system.out.println (  "Accept ()  failed or  Interrupted ... " );      }    }    System.out.println (  "Thread exitinG under request " );   }} 

The following is the output after running the code in Listing E:

Starting thread ...

Waiting for connection ...

Asking thread to stop ...

Accept () failed or interrupted ...

Thread exiting under request ...

Stopping application ...


How to interrupt a Java thread

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.