JAVA correctly stops a thread __java

Source: Internet
Author: User
How to stop a thread correctly

This article (How to stop thread) gives a good answer to the proper stopping of threads, summed up 3 points below (when stopping threads):

1. Use the violate Boolean variable to identify whether the thread is stopped

2. When stopping a thread, you need to invoke the interrupt () method of the stop thread, because the thread may be waiting () or sleep () to increase the immediacy of the stop thread

3. For blocking IO processing, try to use Interruptiblechannel instead of blocking IO

The core is as follows:

If you are are writing your own small thread then you should follow the following code.

 private volatile Thread mythread;
        public void Stopmythread () {Thread tmpthread = mythread;
        Mythread = null;
        if (tmpthread!= null) {tmpthread.interrupt ();
        } public void Run () {if (Mythread = null) {return;//stopped before started.
            try {//All "run () method" code goes here ...//do some work Thread.yield ();
            Let another thread have some time perhaps to stop this one. if (Thread.CurrentThread (). isinterrupted ()) {throw new Interruptedexception ("Stopped by Ifinterruptedstop" (
            )"); }//Do some more work ...} catch (Throwable t) {//Log/handle all Errors here}} 

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.