How to gracefully and correctly terminate threads in Java

Source: Internet
Author: User
Tags volatile

There are three main ways to terminate threads in Java:

1. Using the Stop () method, has been deprecated. The reason is that stop () is terminated immediately, causing some data to be processed as part of the termination, and the user does not know what data is processed, which is not processed, resulting in incomplete "disability" data, not integrity, so was discarded. So, forget it!

2. Use volatile flag bit

See a simple example:

First, implement a runnable interface in which you define the volatile flag bit and use the flag-bit control program to run in the Run () method

 Public  class myrunnable implements Runnable {      //Define exit flag, True will always execute, false will exit loop    //Use volatile to ensure visibility, a change in the flag, everywhere to go to main memory to read the new value, instead of using the cache     Public volatile BooleanFlag =true; Public void Run() {System.out.println ("section"+ Thread.CurrentThread (). GetName () +"Thread Creation");Try{Thread.Sleep ( +L); }Catch(Interruptedexception e)          {E.printstacktrace (); }//Exit flag effective Location         while(flag) {} System.out.println ("section"+ Thread.CurrentThread (). GetName () +"Thread Termination"); }  }

Then, create the thread in the main () method, modify the flag bit at the appropriate time, and terminate the running thread.

 Public classtreadtest { Public Static void Main(string[] arg) throws Interruptedexception {myrunnable runnable =NewMyrunnable ();//Create 3 threads         for(inti =1; I <=3; i++) {Thread thread =NewThread (runnable, i +"");          Thread.Start (); }//thread hibernationThread.Sleep ( -L); System. out. println ("——————————————————————————");//Modify the exit flag to terminate the threadRunnable.flag =false; }  }

Finally, run the results as follows:

第1个线程创建第2个线程创建第3个线程创建--------------------------第3个线程终止第1个线程终止第2个线程终止

3, using interrupt () interrupt mode, note that using the interrupt () method to interrupt a running thread will only modify the interrupt status bit, can be judged by isinterrupted (). If you use the interrupt () method to break a thread in a block, the interruptedexception exception is thrown, the exception can be caught by catching, and then the thread is terminated after processing. In some cases, we cannot judge the state of a thread, so it is important to think carefully when using the interrupt () method.

First type: terminating in operation

 Public  class MyThread extends Thread {     Public void Run(){Super. Run ();Try{ for(intI=0; i<500000; i++) {if( This. Interrupted ()) {System.out.println ("The thread has terminated and the For loop is no longer executing");Throw NewInterruptedexception (); } System.out.println ("i="+ (i+1)); } System.out.println ("This is the statement outside the for loop and will be executed"); }Catch(Interruptedexception e) {System.out.println ("into the catch in the Mythread.java class ... ");        E.printstacktrace (); }    }}
publicclass Run {    publicstaticvoidmain(String args[]){        new MyThread();        thread.start();        try {            Thread.sleep(2000);            thread.interrupt();        catch (InterruptedException e) {            e.printStackTrace();        }    }}

The results of the operation are as follows:

...i=203798i=203799i=203800for循环不再执行进入MyThread.java类中的catch了。。。java.lang.InterruptedException    at thread.MyThread.run(MyThread.java:13)

Second type: Blocking status (sleep,wait, etc.) termination

public   Class  mythread  extends  thread  { public  void  run  () {super . Run (); try  {System.out.println ( "thread begins ... "); Thread.Sleep (200000 ); System.out.println (" thread ends. "); } catch  (interruptedexception e) {System.out.println (" is stopped in slumber, into a catch, and the result of calling the Isinterrupted () method is: " + this . isinterrupted ()); E.printstacktrace (); } }}
线程开始。。。在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:falsejava.lang.InterruptedException: sleep interrupted    Method)    at thread.MyThread.run(MyThread.java:12)

From the printed result, if a thread is stopped in the sleep state, the catch statement is entered and the stop state value is cleared to false.

The previous experiment was to sleep and then stop with interrupt (), and the opposite operation should also be noted in the learning process:

 Public  class MyThread extends Thread {     Public void Run(){Super. Run ();Try{System.out.println ("Thread start ... "); for(intI=0; i<10000; i++) {System.out.println ("i="+ i); } thread.sleep (200000); System.out.println (the thread ends. "); }Catch(Interruptedexception e) {System.out.println ("Stop first, then sleep, enter catch exception");        E.printstacktrace (); }    }} Public  class Run {     Public Static void Main(String args[]) {Thread thread =NewMyThread ();        Thread.Start ();    Thread.Interrupt (); }}

Operation Result:

i=9998i=9999先停止,再遇到sleep,进入catch异常java.lang.InterruptedException: sleep interrupted    Method)    at thread.MyThread.run(MyThread.java:15)

How to gracefully and correctly terminate threads in Java

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.