線程的停止和中斷

線程停止有四種種情況:
1.run運行結束
2.異常退出
3.stop強制中止,這個不推薦使用,存在風險,比如說掃尾清理工作未完成,關閉資源未完成 就退出了。
4.interrupt方法中斷線程, 需要主動編碼配合,寫中斷邏輯,但是可控。

調用interrupt()方法只是打了個退出標誌,並非真正的退出,退出邏輯需要自己寫。

package ThreadCheat1.interrupt;

/**
 * @ClassName InterruptDemo
 * @Author laixiaoxing
 * @Date 2019/4/22 下午12:35
 * @Description 驗證中斷
 * @Version 1.0
 */
public class InterruptDemo {

   static class Mythread implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i <500000 ; i++) {
                System.out.println("i="+(i+1));
            }
        }
    }


    public static void main(String[] args) {

        Mythread mythread=new Mythread();
        Thread thread=new Thread(mythread);
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }

}


輸出結果:
在這裏插入圖片描述

說明調用interrupt時候並未退出.

Thread中提供了兩個方法
1.this.interrupted 測試當前線程是否中斷(如果是中斷,則會清除中斷的狀態標誌,也就是如果中斷了線程,第一次調用這個方法返回true,第二次繼續調用則返回false)
2.this.isInterrupted 測試線程是否已經中斷(不清除中斷的狀態標誌)

可以手動編碼,在線程代碼邏輯裏面去用interrupted判斷,如果中斷了,就執行中斷邏輯。
一般來說,用拋出一箇中斷異常的處理比較好一些,因爲拋出異常之後,這個線程肯定就中止了,然後外部業務代碼捕獲中斷異常之後,進行自己想要的處理。

package ThreadCheat1.interrupt;

/**
 * @ClassName InterruptDemo
 * @Author laixiaoxing
 * @Date 2019/4/22 下午12:35
 * @Description 驗證中斷
 * @Version 1.0
 */
public class InterruptDemo {

    static class Mythread implements Runnable {
        @Override
        public void run() {
            try {
                for (int i = 0; i < 500000; i++) {
                    if (Thread.interrupted()) {
                        System.out.println("檢測到中斷狀態");
                        throw new InterruptedException();
                    }
                    System.out.println("i=" + (i + 1));
                }

                System.out.println("其他處理邏輯,中斷後不執行");
            } catch (InterruptedException e) {
                System.out.println("捕獲到中斷異常之後");
                e.printStackTrace();
            }
            }
        }


        public static void main(String[] args) {

            Mythread mythread = new Mythread();
            Thread thread = new Thread(mythread);
            thread.start();
            try {
                Thread.sleep(2000);
                thread.interrupt();//中斷
            } catch (InterruptedException e) {
                System.out.println("main catch");
                e.printStackTrace();
            }
        }

    }

在這裏插入圖片描述

不使用stop 而是使用intterupt和 intterupted去主動配合中斷,使線程中斷更加可控。

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