如何停止java線程

來源:互聯網
上載者:User

簡介

在Java的多線程編程中,java.lang.Thread類型包含了一些列的方法start(), stop(), stop(Throwable) and suspend(), destroy() and resume()。通過這些方法,我們可以對線 程進行方便的操作,但是這些方法中,只有start()方法得到了保留。

在Sun公司的一篇文章《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? 》中詳細講解了捨棄這些方法的原因。那麼,我們究竟應該如何停止線程呢?

建議使用的方法

在《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? 》中,建 議使用如下的方法來停止線程:

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();
         }
     }

關於使用volatile關鍵字的原因,請查看 http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930。

當線程處於非運行(Run)狀態

當線程處於下面的狀況時,屬於非運行狀態:

* 當sleep方法被調用。

*當wait方法被調用。

*當被I/O阻塞,可能是檔案或者網路等等。

當線程處於上述的狀態時,使用前面介紹的方法就不可用了。這個時候,我們可以使用 interrupt()來打破阻塞的情況,如:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.