How to stop Java threads

Source: Internet
Author: User
Tags deprecated sleep thread volatile

Brief introduction

In Java multithreaded programming, the Java.lang.Thread type contains some of the column's method 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 a Sun company article "Why are Thread.stop, thread.suspend and Thread.Resume deprecated?" Explains the reasons for abandoning these methods in detail. So how exactly should we stop the thread?

Suggested methods of use

In the Why are Thread.stop, thread.suspend and Thread.Resume deprecated? , we recommend that you stop the thread by using the following methods:

private volatile Thread blinker;
     public void stop() {
         blinker = null;
     }
     public void run() {
         Thread thisThread = Thread.currentThread();
         while (blinker == thisThread) {
             try {
                 thisThread.sleep(interval);
             } catch (InterruptedException e){
             }
             repaint();
         }
     }

For a reason to use the volatile keyword, see http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930.

When a thread is in a non-running (run) state

When a thread is in the following state, it is not running:

* When the sleep method is invoked.

* When the wait method is invoked.

* When blocked by I/O, may be a file or network, and so on.

When the thread is in the above state, using the method described earlier is not available. At this time, we can use interrupt () to break the blocking situation, such as:

public void stop() {
         Thread tmpBlinker = blinker;
         blinker = null;
         if (tmpBlinker != null) {
            tmpBlinker.interrupt();
         }
     }

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.