多線程學習-停止線程

引入

停止線程是在多線程開發時很重要的技術點,掌握此技術可以對線程的停止進行有效的處理。停止一個線程意味着在線程處理完任務之前停掉正在做的操作,也就是放棄當前操作。

判斷線程是否是停止狀態

Thread類中提供了兩種方法,interrupted()和isInterrupted(),下面做詳細介紹。

  1. interrupted( )方法

    方法聲明:public static boolean interrupted()
    含義:測試當前線程是否已經中斷。線程中斷狀態由該方法清除。換句話說,如果連續兩次調用此方法,則第二次調用將返回false。

  2. isInterrupted( )方法

    方法聲明:public boolean interrupted()
    含義:測試線程是否已經中斷。不清楚狀態標識。

中斷線程的方法

當線程的run方法執行方法體中最後一條語句後,並經由垂直型return語句返回時,或者出現了在方法中沒有捕獲的異常時,線程將終止。在java的早期版本中還有一個stop方法,後被棄用。iterrupt方法可以用來請求終止線程,當對一個線程調用interrupt方法時,線程的中斷狀態將被置位。這是每一個線程都具有的boolean標誌。每個線程都應該不時的檢查這個標誌,以判斷線程是否被中斷。但是,如果線程被阻塞(sleep或wait),就無法檢測中斷狀態。這是會產生InterruptedException異常的地方。

package page.thread.two;

public class MyThread extends Thread{

    public void run(){
        super.run();
        try {
            for(int i=0;i<500000;i++){
                if(this.isInterrupted()){
                    System.out.println("已經是停止狀態了,要退出");
                    throw new InterruptedException();
                }
                System.out.println("i="+(i+1));
            }
            System.out.println("在for之下");
        } catch (InterruptedException e) {
            System.out.println("進入MyThread類run方法中的catch");
            e.printStackTrace();
        }
    }
}

package page.thread.two;

public class Run {

    public static void main(String[] args) throws InterruptedException {
        try{
            MyThread mt=new MyThread();
            mt.start();
            Thread.sleep(2000);
            mt.interrupt();
        }catch(InterruptedException e){
            System.out.println("main catch");
            e.printStackTrace();
        }
    }
}

運行結果:
這裏寫圖片描述

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