淺析Java線程的正確停止,淺析Java線程正確

來源:互聯網
上載者:User

淺析Java線程的正確停止,淺析Java線程正確
線程錯誤終止之destroy與stop方法

記得以前初學Java的時候,由於缺少對鎖、同步、非同步等這些線程的知識,想當然的以為destroy與stop方法都能正確的停止Java線程的執行。但是,後來隨著工作的積累,以及對安全執行緒的一些理解,慢慢認識到這兩個方法是有問題的,並且這兩方法也早已在java doc上被指名是棄用的。

destroy()這個方法其實根本沒幹什麼事情,只是拋出了一個NoSuchMethodError,所以說該方法無法終止線程,因此不能望文生意:

/**     * Throws {@link NoSuchMethodError}.     *     * @deprecated This method was originally designed to destroy this     *     thread without any cleanup. Any monitors it held would have     *     remained locked. However, the method was never implemented.     *     If if were to be implemented, it would be deadlock-prone in     *     much the manner of {@link #suspend}. If the target thread held     *     a lock protecting a critical system resource when it was     *     destroyed, no thread could ever access this resource again.     *     If another thread ever attempted to lock this resource, deadlock     *     would result. Such deadlocks typically manifest themselves as     *     "frozen" processes. For more information, see     *     <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">     *     Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.     * @throws NoSuchMethodError always     */    @Deprecated    public void destroy() {        throw new NoSuchMethodError();    }
對於stop方法,其本質就是因為會線程不安全,它會直接終止run方法的調用,並且會拋出一個ThreadDeath錯誤,如果線程持有某個對象鎖的話,會完全釋放鎖,導致對象狀態不一致。具體細節可以看官方的java doc;
Deprecated. This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see <a target=_blank href="http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>.

線程的正確終止

在上述的destroy和stop方法都一一被否定之後,那還有什麼方式能夠正確多終止線程呢?總的來說,在java中有兩種解決方案:

  • 標誌,在run方法中通過一個標記來進行結束,由於該方式很尋常就不做舉例
  • interrupt,通過異常中斷

下面就主要針對interrupt進行展開探討。

/**     * Interrupts this thread.     *     * <p> Unless the current thread is interrupting itself, which is     * always permitted, the {@link #checkAccess() checkAccess} method     * of this thread is invoked, which may cause a {@link     * SecurityException} to be thrown.     *     * <p> If this thread is blocked in an invocation of the {@link     * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link     * Object#wait(long, int) wait(long, int)} methods of the {@link Object}     * class, or of the {@link #join()}, {@link #join(long)}, {@link     * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},     * methods of this class, then its interrupt status will be cleared and it     * will receive an {@link InterruptedException}.     *     * <p> If this thread is blocked in an I/O operation upon an {@link     * java.nio.channels.InterruptibleChannel </code>interruptible     * channel<code>} then the channel will be closed, the thread's interrupt     * status will be set, and the thread will receive a {@link     * java.nio.channels.ClosedByInterruptException}.     *     * <p> If this thread is blocked in a {@link java.nio.channels.Selector}     * then the thread's interrupt status will be set and it will return     * immediately from the selection operation, possibly with a non-zero     * value, just as if the selector's {@link     * java.nio.channels.Selector#wakeup wakeup} method were invoked.     *     * <p> If none of the previous conditions hold then this thread's interrupt     * status will be set. </p>     *     * <p> Interrupting a thread that is not alive need not have any effect.     *     * @throws  SecurityException     *          if the current thread cannot modify this thread     *     * @revised 6.0     * @spec JSR-51     */    public void interrupt() {        if (this != Thread.currentThread())            checkAccess();        synchronized (blockerLock) {            Interruptible b = blocker;            if (b != null) {                interrupt0();           // Just to set the interrupt flag                b.interrupt(this);                return;            }        }        interrupt0();    }
根據java源碼摘出的interrupt方法注釋和方法體的實現,可以歸納為:通過調用interrupt方法可以使得處於阻塞狀態的線程拋出一個異常,即interrupt方法可以用來中斷一個正處於阻塞狀態的線程;另外,改方法還會設定線程的中斷狀態(註:isInterrupted()可以用來查詢中斷狀態)。

實踐檢驗真理實驗interrupt能否中斷處於非阻塞狀態的線程

代碼:

public class ThreadTest {/** * @param args */public static void main(String[] args) {WorkThread wThread = new WorkThread();wThread.start();System.out.println("開始調用wThread.interrupt()");wThread.interrupt();System.out.println("結束調用wThread.interrupt()");}}class WorkThread extends Thread {public void run() {for (int i = 0; i < Byte.MAX_VALUE;) {System.out.println("背景工作執行緒運行" + (++i));}}}
運行結果:


實際是列印到127結束,由於太長,只截取部分。從中可以發現,for迴圈會一直運行直到變數i的值超出Byte.MAX_VALUE。

結論:interrupt無法中斷非阻塞狀態的線程。

但是,我門可以換個思路,既然之前提過interrupt方法會設定線程的中斷狀態,那麼我門可以通過isInterrupt()來進行判斷,從而中斷線程。(本質上這種方案時標誌中斷)

上代碼,只對WorkThread的條件迴圈增加一個標誌判斷——isInterrupt():

class WorkThread extends Thread {public void run() {for (int i = 0; i < Byte.MAX_VALUE && isInterrupted();) {System.out.println("背景工作執行緒運行" + (++i));}}}
運行結果:


從結果上來看,interrupt配合isInterrupt()能夠中斷非阻塞狀態的線程。註:本質還是標誌中斷

interrupt能否中斷阻塞狀態的線程

上代碼:

public class ThreadTest {/** * @param args */public static void main(String[] args) {WorkThread wThread = new WorkThread();wThread.start();System.out.println("開始調用wThread.interrupt()");wThread.interrupt();System.out.println("結束調用wThread.interrupt()");}}class WorkThread extends Thread {public void run() {System.out.println("背景工作執行緒sleep");for (int i = 0; i < Byte.MAX_VALUE;) {try {sleep(10 * 1000);System.out.println("背景工作執行緒運行"+(++i));} catch (InterruptedException e) {System.out.println("背景工作執行緒InterruptedException");break;}}System.out.println("背景工作執行緒運行完畢");}}
運行結果:

從程式到運行結果來看,當背景工作執行緒進入sleep(即阻塞)的時候,調用interrupt方法,將會促使線程拋出異常。

結論:interrupt能夠中斷阻塞狀態的線程。

總結

Java沒有立即終止線程的機制,Java的Thread類提供的destroy和stop方法無法正確終止線程,只能通過標誌或者interrup方法來進行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.