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.

Package test,  
 
public class Threadflag extends Thread  

    Public volatile Boolean exit = FALSE; &NBSP
 
    public void Run ()  
    { 
         while (!exit); &NBSP
   }  
    public static void Main (string[] args) throws Exception & nbsp
    { 
        threadflag thread = new Threadflag (); nbsp
        Thread.Start ();  
         Sleep (5000); The main thread is delayed by 5 seconds  
        thread.exit = true; //terminating threads 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 test;

public class Threadinterrupt extends Thread
{
public void Run ()
{
Try
{
Sleep (50000); 50 seconds delay
}
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!");
}
}

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 a 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.