Multithreading (iv) How to stop a thread

Source: Internet
Author: User
Tags deprecated thread class thread stop

Methods (including kill and hang) that can stop a thread are provided in the thread class:

@Deprecated
Public final void Stop () {}
    @Deprecated
Public final void suspend() {}
    
Stop and suspend add a deprecated comment, which means that the method has been deprecated. So why not recommend the use of both methods? Is there any other way to stop threading?

1, Stop () will immediately kill the thread, there is no guarantee that the atomic operation can be completed successfully, there is a risk of data errors. Stop immediately stops the thread from running and exits directly, regardless of where the thread is executed or unlocked.

The following code:

 intaccount01 = 10; intaccount02= 0; Object Lock=NewObject ();  Public voidTeststop () {classStoprunnableImplementsRunnable {@Override Public voidrun () {//Request account01 + account02 =10 established                 while(true) {                    synchronized(lock) {//locking guarantees the atomicity of the Operationaccount01--;Sleep (200);//Sleep Simulation Execution Processaccount02++; } }}} thread thread=NewThread (Newstoprunnable ());        Thread.Start (); Sleep (1300);Thread.stop (); System.out.println ("ACCOUNT01:" + account01 + "\naccount02:" +account02); }
    void sleep (int time ) {        trycatch (Interruptedexception e) {e.printstacktrace ();}}  

The results of the operation are as follows:

Account01:36

Obviously there is no guarantee that both the and is 10. In the process of thread looping, the last lock loop body is not completed and the data error occurs. In addition, after the Stop method is executed, the thread immediately releases the lock, which also results in an atomic operation failure data exception.

Official notes:

Forces the thread to stop executing.
It is permitted to stop a thread this has not yet been started.
If The thread is eventually started, it immediately terminates.

2. Suspend () does not kill the thread, just suspends the thread and stops the thread from running. However, the lock is not released after the suspension, so that if there are many other threads waiting for the lock, the program will deadlock.

The following code:

    intaccount01 = 10; intaccount02= 0; Object Lock=NewObject ();  Public voidTeststop () {classStoprunnableImplementsRunnable {@Override Public voidrun () {//Request account01 + account02 =10 established                 for(intI =0;i<5;i++){                    synchronized(lock) {//locking guarantees the atomicity of the Operationaccount01--; System.out.println ("..." +thread.currentthread (). GetName ());//in order to see the thread stop adding the output thread name OperationSleep (200);//Sleep 200msaccount02++; } }}} Thread thread01=NewThread (Newstoprunnable ()); Thread01.setname ("Thread01"); Thread thread02=NewThread (Newstoprunnable ()); Thread02.setname ("THREAD02");        Thread01.start ();        Thread02.start (); Sleep (500);        Thread01.suspend ();  while(true) {Sleep (1000); System.out.println ("ACCOUNT01:" + account01 + "account02:" + account02+ "thread01 isAlive:" +thread01.isalive () + "thread02 isAlive:" +thread02.isalive ()); }    }

The results of the operation are as follows:

..... thread01
..... thread01
..... thread01
isalive:true thread02 isalive:true
Account01:7 account02:2 thread01 isalive:true thread02 isalive:true
Account01:7 account02:2 thread01 isalive:true thread02 isalive:true
Account01:7 account02:2 thread01 isalive:true thread02 isalive:true
Account01:7 account02:2 thread01 isalive:true thread02 isalive:true
Account01:7 account02:2 thread01 isalive:true thread02 isalive:true

As can be seen from the results, THREAD01 has been running, and THREAD02 did not execute to the Run method once. Then, after executing thread01.suspend (), two threads stop running the Run method. But two threads are not dead at the same time.

Suspend is executed only for THREAD01 in the code, then if THREAD02 acquires the lock it should continue to be executed by THREAD02, but not, the lock lock is held by THREAD01 and is not released after it has been suspended.

In fact, when using the Suspend () method, it needs to be used in conjunction with the resume ().

.... 
....
Sleep (500); Thread01.suspend (); intTime = 0;//Add a time count that is released after looping three times while(true) { time++; if(Time ==3) {thread01.resume ();//Releasing Threads} sleep (1000); System.out.println ("ACCOUNT01:" + account01 + "account02:" + account02+ "thread01 isAlive:" +thread01.isalive () + "thread02 isAlive:" +thread02.isalive ()); }

The results of the implementation are as follows:

..... thread01.....thread01.....thread01account01:7 Account02:2 thread01 isAlive:trueTHREAD02 isAlive:trueaccount01:7 Account02:2 thread01 isAlive:trueTHREAD02 isAlive:true.....  thread01//release to continue running ... thread01.....thread02//thread01 release lock, THREAD02 get lock to continue running..... thread02 ... THREAD02ACCOUNT01:2 Account02:7thread01 isAlive:falseThread02isAlive:true//thread01 death, Thread02 alive..... thread02.....thread02account01:0 account02:10 thread01 isAlive:falseTHREAD02 isAlive:falseaccount01:0 account02:10 thread01 isAlive:falseTHREAD02 isAlive:falseaccount01:0 account02:10 thread01 isAlive:falseTHREAD02 isAlive:falseaccount01:0 account02:10 thread01 isAlive:falseTHREAD02 isAlive:false

As you can see, after Thread01.resume () THREAD01 continues to run, and then runs the end release lock, THREAD02 then runs up to see that thread01 is dead, and THREAD02 is still alive. Until all two threads have ended. If the normal use of suspend () and resume () is not too big a problem, but only when the lock is involved in a long time need extra care. R If the lock is not used, then the suspension of one of the threads does not affect the execution of other threads.

For the public void interrupt () {} method, the method simply interrupts the blocking state of the thread (seleep, wait, join, and Io/nio operations), and when the interrupt method is called, Interruptedexception/Closedbyinterruptexception will be thrown if the thread is in a blocked state . Only the exception is captured in the program and does not affect subsequent operations. For a thread that is not in a blocking state, calling the interrupt method has no effect. So interrupt strictly does not belong to the method of stopping the thread.

So, exactly how to stop the thread safely?

Rules to follow: let the thread stop itself.

Two methods : 1, the thread task execution completes, the successful end exits. 2, set the termination flag bit, in the loop when the termination flag bit detection, if set to terminate the status of return to end the thread.

For example: 1, thread execution completes automatic exit:

             Public void run () {                for (int i = 0;i<10;i++){// Loop 10 times after the Run method ends auto End thread                     System.out.println (Thread.CurrentThread (). GetName ());                }            }

2, set the STOP flag.

    BooleanIsstop =false;//stop flag bit change to true when you need to end a thread     Public voidTestinterrupt () {Thread th=NewThread (NewRunnable () {@Override Public voidrun () { while(true){                    if(Isstop) {//terminating a thread when it needs to end a thread//dosomething to do some finishing work                        return;                } System.out.println (Thread.CurrentThread (). GetName ()); }            }        });

When the terminating flag bit is set, the thread does not terminate immediately, and the exit operation is performed only when the loop to the flag bit is judged, so that the exit logic can be executed in the appropriate place in the loop body, which guarantees the smooth completion of the atomic operation and the release of the lock.

for executorservice void shutdown (); Method, the method simply stops the thread pool from accepting new tasks while waiting for the committed thread to end, and does not stop the threads. Therefore, this method does not belong to the method of stopping the thread.

=========================================

original link: multi-threaded (four) How to stop the thread Reprint Please specify the source!

=========================================

---end

Multithreading (iv) How to stop 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.