【java】【09】正確處理Thread.sleep(10)的異常

參考文檔

https://blog.csdn.net/blog_empire/article/details/86693851

1.demo

package com.br.doublelive.redis;

import javafx.concurrent.Worker;

public class InterruptExceptionTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Worker());
        t.start();

        Thread.sleep(100);
        t.interrupt();

        System.out.println("Main thread stopped.");
    }

    public static class Worker implements Runnable {

        @Override
        public void run() {
            System.out.println("Worker started.");

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {

                System.out.println("拋出異常JVM會清除線程的中斷狀態    Worker IsInterrupted--------: " +
                        Thread.currentThread().isInterrupted());

                // TODO: 2019/1/29 對拋出的InterruptedException的正確處理應該是設置Thread.currentThread().interrupt();
                Thread.currentThread().interrupt();
                System.out.println("執行interrupt()設置線程的中斷狀態 Worker IsInterrupted--------: " +
                        Thread.currentThread().isInterrupted());
                /**
                 * 清除線程的中斷狀態
                 */
                Thread.interrupted();

                System.out.println("清除線程的中斷狀態interrupted();  Worker IsInterrupted--------: " +
                        Thread.currentThread().isInterrupted());
            }

            System.out.println("Worker stopped.");
        }
    }
}

2.以上代碼執行結果

Worker started.
拋出異常JVM會清除線程的中斷狀態    Worker IsInterrupted--------: false
執行interrupt()設置線程的中斷狀態 Worker IsInterrupted--------: true
清除線程的中斷狀態interrupted();  Worker IsInterrupted--------: false
Worker stopped.
Main thread stopped.

3.如果把Thread.interrupted();註釋掉

Worker started.
Main thread stopped.
拋出異常JVM會清除線程的中斷狀態    Worker IsInterrupted--------: false
執行interrupt()設置線程的中斷狀態 Worker IsInterrupted--------: true
清除線程的中斷狀態interrupted();  Worker IsInterrupted--------: true
Worker stopped.

4.如果把Thread.currentThread().interrupt()註釋掉

Worker started.
Main thread stopped.
拋出異常JVM會清除線程的中斷狀態    Worker IsInterrupted--------: false
執行interrupt()設置線程的中斷狀態 Worker IsInterrupted--------: false
清除線程的中斷狀態interrupted();  Worker IsInterrupted--------: false
Worker stopped.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章