線程的中斷

今天,在學習線程中斷的過程中,學到了之前不知道的新知識。線程中斷避免使用Thread提供的stop()方法。正確的方法是使用interrupt()方法,案例如下:

public class MyRunnable implements Runnable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
        //使線程休眠5秒
        thread.sleep(5000);
        //中斷線程
        //thread.stop();
        thread.interrupt();
    }
    @Override
    public void run() {
        int i = 0;
//判斷線程沒有中斷並且小於1000000的情況下,執行循環邏輯
//        while(!Thread.interrupted() && i < 1000000){
        while(!Thread.currentThread().isInterrupted() && i < 1000000){
            System.out.println(i ++);
        }
        System.out.println("Thread.currentThread().isInterrupted() = " +Thread.currentThread().isInterrupted());
    }
}

解釋:如代碼所示,啓動線程5秒之後中斷線程。線程執行過程中,判斷線程是否被中斷,如果中斷退出循環。

通過上述來看,感覺Thread提供了interrupt()和isInterrupted()配合使用。在線程中斷後,可以利用isInterrupted()方法,人爲的來控制線程中斷後,需要處理的邏輯,相比stop()中斷線程方法顯得很靈活。並且,java已經棄用了stop()方法,相關說明java api有解釋,但我還理解不了。

注意:

1.Thread.interrupted()和Thread.currentThread().isInterrupted()方法都可以獲取判斷終止線程的標誌。區別在於Thread.interrupted()獲取線程終止狀態爲true後,會重置狀態。Thread.currentThread().isInterrupted()獲取線程終止狀態爲true後,不會重置。

查看源碼:

//Thread.interrupted()方法調用的源碼    
public static boolean interrupted() {        
    return currentThread().isInterrupted(true);
}   

 
//Thread.currentThread().isInterrupted()方法調用的源碼
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.
     * 中文解釋:如果出入參數爲true,那麼終止狀態被重置,如果爲false不重置。
     */
    private native boolean isInterrupted(boolean ClearInterrupted);

2.如果正在執行的線程在休眠時,線程終止,那麼線程會拋java.lang.InterruptedException異常,並且線程終止狀態會被重置。例子如下:

public class MyRunnable implements Runnable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
        thread.sleep(5000);
//        thread.stop();
        thread.interrupt();
    }
    @Override
    public void run() {
        int i = 0;
//        while(!Thread.interrupted() && i < 1000000){
        while(!Thread.currentThread().isInterrupted() && i < 1000000){
            System.out.println(i ++);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread.currentThread().isInterrupted() = " +Thread.currentThread().isInterrupted());
    }
}

執行上述代碼,在while循環過程中,線程被終止。跳出循環,當前線程終止狀態爲true,在執行Thread.sleep(1000);這行代碼時,拋出java.lang.InterruptedException異常,同時線程終止狀態重置爲false。

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