停止線程

java多線程啓動線程調用start()方法,停止線程使用stop()方法。嗯,停止線程就是這麼簡單,但是現在stop()方法已經被標記過時了。

@Deprecated
    public final void stop() {
        SecurityManager security = System.getSecurityManager();

不止是stop()方法,還有許多,例如resume(), suspend()等方法都過時了,搜索文章 Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?  可以瞭解這些方法過時的原因。

正確停止一個線程涉及到了3個方法,分別是 interrupt(), interrupted(), isInterrupted()。其中,interrupt()是停止線程的方法,interrupted()和 isInterrupted()兩個返回布爾值的方法。

線程對象調用interrupt()方法之後,並沒有真正的停止,而是打上了一個標記,可以改變interrupted()和 isInterrupted()的返回值。那麼,interrupted()和 isInterrupted()有什麼區別呢?看源碼可以知道,interrupted()是一個靜態方法,用來判斷當前線程(注意不一定是調用interrupted()方法的線程)是否打上了標記,isInterrupted()用於判斷調用該方法的線程對象是否打上了標記。並且還可以看到,這兩個方法都調用了一個native的私有方法isInterrupted, 裏面有個形參ClearInterrupted,註釋的意思是是否清除標記。通過代碼嘗試,得知了interrupted()方法具有清除標記的功能,而isInterrupted()方法沒有,清除標記的功能是指,線程被打上停止標記後,第一次調用interrupted()方法會返回true,第二次則會清除標記,從而返回false。

public static boolean interrupted() {
        return currentThread().isInterrupted(true);
}

public boolean isInterrupted() {
        return isInterrupted(false);
}

/**
     * Tests if some Thread has been interrupted.  The interrupted state
     * is reset or not based on the value of ClearInterrupted that is
     * passed.
     */
private native boolean isInterrupted(boolean ClearInterrupted);

這樣,我們就知道了如何正確的在一個線程中停止另外一個線程。就是在一個線程中,將要停止的線程調用interrupt()方法,然後在線程代碼中使用interrupted()和 isInterrupted()判斷是否爲true來決定。

那如何在一個線程中停止當前線程呢?直接讓run方法走完不就可以了嘛。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章