How Java correctly stops a thread

Source: Internet
Author: User

The thread class has the start (), Stop () method, but the stop method has been discarded.

Usually also useful, share a variable, the equivalent of a flag, constantly check the flag, determine whether to exit the thread

If there is blocking, you need to use the thread's interrupt () side interrupt blocking, the threads start checking flags (PS: Throwing an exception does not exit the loop)

------------------------------------------------------------I am the copy split line----------------------------------------------

Original source: http://blog.163.com/xh_ding/blog/static/193903289201341685931689

How to stop Java threads has always been a problem with developing multi-threaded routines. A lot of people have asked me, so here's a summary of the hope that more people will know how to safely end a running thread in Java.

In multithreaded programming in Java, the Java.lang.Thread type contains methods for some columns, start (), Stop (), Stop (Throwable) and suspend (), Destroy () and resume (). With these methods, we can easily manipulate threads, but only the start () method is preserved in these methods. In the JDK help document and a Sun company article "Why is Thread.stop, Thread.Suspend and Thread.Resume Deprecated?" Explains the reasons for abandoning these methods. So how exactly should we stop the thread? Here we introduce two ways: 1. How to use shared variables

In this way, a shared variable is introduced because the variable can be used by multiple threads that perform the same task as a signal to interrupt the execution of the thread in the notification.  public class Threadflag extends thread {     public volatile Boolean exit = false;  & nbsp   public void Run ()      {         while (!exit);    } &N Bsp   public static void main (string[] args) throws exception     {         Threa Dflag thread = new Threadflag ();         Thread.Start ();         sleep (3 000); Main Thread Delay 3 sec          Thread.exit = true;  //terminating thread thread         Thread.Join ();         SYSTEM.OUT.PRINTLN ("Thread exits!");     } }  An exit flag is defined in the above code exit, and when Exit is true, the while loop exits with the default value of exit 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.   In Why is Thread.stop, Thread.suspend,thread.resume and Runtime.runfinalizErsonexit Deprecated?, we recommend that you use the following method to stop a thread:  private volatile thread blinker;     public void Stop () {& nbsp;        blinker = null;    }     public void Run () {   & nbsp     Thread thisthread = Thread.CurrentThread ();         while (blinker = = Thisthread) {              Try {                 THISTHR Ead.sleep (interval);            } catch (Interruptedexception e) {            }             repaint ();        }     } 2. Terminating a thread using the interrupt method   How do I stop a thread if it is blocked by waiting for certain events to occur? This often happens, such as when a thread is blocked because it needs to wait for keyboard input, or calls the Thread.Join () method, or the Thread.Sleep () method, calls the Serversocket.accept () method in the network. Or, when the Datagramsocket.receive () method is called, it is possible to cause the thread to block, leaving the thread in a non-operational state, even if the shared variable of the thread is set to true in the main program, but the thread cannot check the loop flag at this time, and of course it cannot be interrupted immediately. The suggestion here is not to use the Stop () method, but rather to use the interrupt () method provided by the thread, since the method does not break a running thread, but it can cause a blocked thread to throw an interrupt exception, causing the thread to end the blocking state prematurely. Exit the clogging code.  class MyThread extends Thread {volatile Boolean stop = False; public void Run () {while (!stop) {System.out.prin TLN (GetName () + "is running"), try {sleep (+),} catch (Interruptedexception e) {System.out.println ("Week up from Blcok. ."); Stop = true; Modify the state of the shared variable in the exception handling code}}SYSTEM.OUT.PRINTLN (GetName () + "is exiting ...");}  class InterruptThreadDemo3 {public static void main (string[] args) throws Interruptedexception {MyThread M1 = new My Thread (); SYSTEM.OUT.PRINTLN ("Starting thread ..."); M1.start (); Thread.Sleep (3000); System.out.println ("Interrupt thread ...:" + m1.getname ()); m1.stop = true; Set the shared variable to Truem1.interrUpT (); Exit blocking state when blocking Thread.Sleep (3000); The main thread sleeps for 3 seconds to observe the interrupt condition of the thread M1 System.out.println ("Stopping application ...");}}   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.

How Java correctly stops 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.