Thread線程中斷相關方法

public class Demo {

    /*
     * 線程中斷相關方法
     * ------------------------------------------------------------------------------
     * interrupt()
     *         中斷線程:
     *         線程的thread.interrupt()方法是中斷線程,將會設置該線程的中斷狀態位,即設置爲true。
     *         中斷的結果線程是死亡、仍是等待新的任務或是繼續運行至下一步,就取決於這個程序自己。
     *         線程會不時地檢測這個中斷標示位,以判斷線程是否應該被中斷(中斷標示值是否爲true)。它並不像stop()方法那樣會中斷一個正在運行的線程。
     * 
     * interrupted()(static方法)
     *         判斷是不是中斷狀態(會當即清除中斷標示位):
     *         等同於currentThread().isInterrupted(true);
     *         該方法調用後會將中斷標示位清除,即從新設置爲false
     * 
     * isInterrupted()
     *         判斷是不是中斷狀態(不會馬上清除中斷標示位):
     *         等同於isInterrupted(false);
     *         它將線程中斷標示位設置爲true後,不會馬上清除中斷標示位,即不會將中斷標設置爲false
     * 
     * isInterrupted(boolean ClearInterrupted) (private方法)
     *         測試某些線程是否被中斷。
     *         是否清除中斷標示位,基於clearinterrupted是值傳遞。
     *         clearinterrupted爲true時會馬上清除中斷標示位,clearinterrupted爲false時不會馬上清除中斷標示位。
     * 
     * 多說無益,仍是看例子來進行區別吧。
     */

    /**
     * interrupted()和isInterrupted()的區別
     */
    public static void main(String[] args) throws Exception {
        // 建立一個線程組
        ThreadGroup threadGroup = new ThreadGroup("ThreadGroup1");

        // 在該線程組下建立一個線程t1
        Thread t1 = new Thread(threadGroup, new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100000); // 100s
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Thread1");

        // 啓動線程
        t1.start();

        // 中斷線程,會設置該線程的中斷狀態位爲true。
        t1.interrupt();

        // 例子1,調用兩次isInterrupted()方法
        // System.out.println(t1.isInterrupted());  // true
        // System.out.println(t1.isInterrupted());  // false
        /*
         *  結論:
         *      第一次調用isInterrupted()方法的時候,中斷標示位尚未被清除。
         *      第二次調用isInterrupted()方法的時候,中斷標示位已經被清除了。
         *  
         *      isInterrupted()雖然不會【馬上】清除中斷標示位,可是仍是會清除中斷標示位的。關鍵詞:馬上
         */

        // 例子2,先調用interrupted()方法,再調用isInterrupted()方法
        // System.out.println(t1.interrupted());    // false
        // System.out.println(t1.isInterrupted());  // false
        /*
         *  結論:
         *      第一次調用interrupted()方法的時候,中斷標示位已經被清除了。
         *      因此再調用isInterrupted()方法,返回的仍然是false。
         *  
         *      interrupted()會【馬上】清除中斷標示位。關鍵詞:馬上
         */

        //  例子3,先調用isInterrupted()方法,再調用interrupted()方法
        // System.out.println(t1.isInterrupted());  // true
        // System.out.println(t1.interrupted());    // false
        /*
         *  前兩個例子已經有結論的。結果是吻合的。
         */

        // 例子4,調用兩次interrupted()方法
        // System.out.println(t1.interrupted()); // false
        // System.out.println(t1.interrupted()); // false
        /*
         *    前兩個例子已經有結論的。結果是吻合的。
         */

    }
}
相關文章
相關標籤/搜索