Three ways to terminate threads in Java

Source: Internet
Author: User
Tags volatile

There are three ways to terminate a thread in Java. The following were:

1. Use the exit flag to cause the thread to exit normally, that is, the thread terminates when the Run method completes.

2. Use the Stop method to forcibly terminate the thread (this method is not recommended because stop and suspend, resume, can also cause unpredictable results).

3. Use the interrupt method to break the thread.

Let's take a detailed introduction to these three ways.

1. Terminating a thread with an exit flag

When the Run method finishes executing, the thread exits. But sometimes the run method is never finished. Use threads to listen for client requests in a server-side program, or other tasks that require cyclic processing. In this case, it is common to place these tasks in a loop, such as a while loop. If you want the loop to run forever, you can use while (True) {...} To deal with. However, the most straightforward way to make a while loop exit under a particular condition is to set a Boolean flag and control whether the while loop exits by setting this flag to true or false. An example of terminating a thread with an exit flag is given below.

package chapter2;    public class threadflag extends thread   {      public volatile boolean exit = false;         public void run ()        {          while  (!exit);       }      public static void main (String[] args)  throws Exception      {           threadflag thread = new threadflag ();           thread.start ();           sleep (; // ) main thread delay 5 seconds           thread.exit =  true;  //  terminating thread THread          thread.join ();           SYSTEM.OUT.PRINTLN ("Thread exits!");       }  }  

An exit flag is defined in the preceding code exit, and when Exit is true, the while loop exits, The default value for Exit is false. When you define exit, a Java keyword, volatile, is used to synchronize exit, meaning that the value of exit can be modified only by one thread at a time.

2. Terminating a thread by using the Stop method

Use the Stop method to forcibly terminate a running or suspended thread. We can use the following code to terminate the thread:

Thread.stop ();

Although using the above code can terminate a thread, using the Stop method is dangerous, just like suddenly shutting down the computer, rather than shutting down as a normal program, it is not recommended to use the Stop method to terminate the thread.

3. Terminating a thread using the interrupt method

Using the interrupt method to end a thread can be divided into two situations:

(1) The thread is in a blocked state, such as using the Sleep method.

(2) Use while (! Isinterrupted ()) {...} To determine if a thread has been interrupted.

In the first case, using the interrupt method, the sleep method throws a Interruptedexception exception, and in the second case the thread exits directly. The following code demonstrates the use of the interrupt method in the first case.

Package chapter2;    public class threadinterrupt extends thread   {      public void run ()        {          try           {               Sleep (50000);  //  Delay 50 sec           }           catch  (interruptedexception e)            {               system.out.println (E.getmessage ());           }      }      public static  Void main (String[] args)  throws Exception      {           thread thread = new threadinterrupt ();           thread.start ();           System.out.println ("Press any key within 50 seconds to break the thread!");           system.in.read ();           thread.interrupt ();           Thread.Join ();           system.out.println ("Thread has exited!");       }  }  

The result of the above code is as follows:

Press any key within 50 seconds to break the thread! Sleep interrupted thread has exited!

  

After calling the interrupt method, the Sleep method throws an exception and then outputs the error message: Sleep interrupted.

Note: There are two methods in the thread class to determine whether a thread is terminated through the interrupt method. One is static method interrupted (), a non-static method isinterrupted (), the difference between the two methods is interrupted to determine whether the current line is interrupted, and isinterrupted can be used to determine whether other threads are interrupted. So while (! Isinterrupted ()) can also be replaced by while (! Thread.interrupted ()).

Article originated from http://www.bitscn.com/pdb/java/200904/161228_3.html

Three ways to terminate threads in Java

Related Article

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.