Three ways to terminate a thread

Source: Internet
Author: User
Tags volatile

There are three ways to make a terminating thread.

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.

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.

[Java]View Plaincopy
  1. Package chapter2;
  2. Public class Threadflag extends Thread
  3. {
  4. Public Volatile Boolean exit = false;
  5. public Void Run ()
  6. {
  7. while (!exit);
  8. }
  9. public static void Main (string[] args) throws Exception
  10. {
  11. Threadflag thread = new Threadflag ();
  12. Thread.Start ();
  13. Sleep (5000); //main thread delay 5 seconds
  14. Thread.exit = true; //Terminate thread threads
  15. Thread.Join ();
  16. System.out.println ("thread exits!");
  17. }
  18. }


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 only one thread can modify the value of exit at the same 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:

[Java]View Plaincopy
    1. 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.

[Java]View Plaincopy
  1. Package chapter2;
  2. Public class Threadinterrupt extends Thread
  3. {
  4. public Void Run ()
  5. {
  6. Try
  7. {
  8. Sleep (50000); //Delay 50 seconds
  9. }
  10. catch (interruptedexception e)
  11. {
  12. System.out.println (E.getmessage ());
  13. }
  14. }
  15. public static void Main (string[] args) throws Exception
  16. {
  17. Thread thread = new Threadinterrupt ();
  18. Thread.Start ();
  19. System.out.println ("Press any key within 50 seconds to break the thread!");
  20. System.in.read ();
  21. Thread.Interrupt ();
  22. Thread.Join ();
  23. System.out.println ("thread has exited!");
  24. }
  25. }


The result of the above code is as follows:

[Java]View Plaincopy
    1. Press any key within 50 seconds to break the thread!
    2. Sleep interrupted
    3. 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

Transferred from: http://blog.csdn.net/zhanjichun_2008/article/details/6612980

Three ways to terminate a thread (GO)

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.