java中interrupt的使用

來源:互聯網
上載者:User

標籤:cep   strong   救世主   ext   src   修改   boolean   顯示   new t   

通常我們會有這樣的需求,即停止一個線程。在java的api中有stop、suspend等方法可以達到目的,但由於這些方法在使用上存在不安全性,會帶來不好的副作用,不建議被使用。具體原因可以參考Why is Thread.stop deprecated。

在本文中,將討論中斷在java中的使用。

中斷在java中主要有3個方法,interrupt(),isInterrupted()和interrupted()。

  • interrupt(),在一個線程中調用另一個線程的interrupt()方法,即會向那個線程發出訊號——線程中斷狀態已被設定。至於那個線程何去何從,由具體的代碼實現決定。
  • isInterrupted(),用來判斷當前線程的中斷狀態(true or false)。
  • interrupted()是個Thread的static方法,用來恢複中斷狀態,名字起得額??。

接下來,看看具體在代碼中如何使用。

interrupt()不能中斷在運行中的線程,它只能改變中斷狀態而已。

public class InterruptionInJava implements Runnable{    public static void main(String[] args) throws InterruptedException {        Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");        //start thread        testThread.start();        Thread.sleep(1000);        //interrupt thread        testThread.interrupt();        System.out.println("main end");    }    @Override    public void run() {        while(true){            if(Thread.currentThread().isInterrupted()){                System.out.println("Yes,I am interruted,but I am still running");            }else{                System.out.println("not yet interrupted");            }        }    }}

 結果顯示,被中斷後,仍舊運行,不停列印Yes,I am interruted,but I am still running

那麼,如何正確中斷?

既然是只能修改中斷狀態,那麼我們應該針對中斷狀態做些什麼。

public class InterruptionInJava implements Runnable{    public static void main(String[] args) throws InterruptedException {        Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");        //start thread        testThread.start();//        Thread.sleep(1000);        //interrupt thread        testThread.interrupt();        System.out.println("main end");    }    @Override    public void run() {        while(true){            if(Thread.currentThread().isInterrupted()){                System.out.println("Yes,I am interruted,but I am still running");                return;            }else{                System.out.println("not yet interrupted");            }        }    }}

修改代碼,在狀態判斷中如上,添加一個return就okay了。但現實中,我們可能需要做的更通用,不禁又要發出天問,如何中斷線程?答案是添加一個開關

public class InterruptionInJava implements Runnable{    private volatile static boolean on = false;    public static void main(String[] args) throws InterruptedException {        Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");        //start thread        testThread.start();        Thread.sleep(1000);        InterruptionInJava.on = true;        System.out.println("main end");    }    @Override    public void run() {        while(!on){            if(Thread.currentThread().isInterrupted()){                System.out.println("Yes,I am interruted,but I am still running");            }else{                System.out.println("not yet interrupted");            }        }    }}

會輸出類似結果,這表明是成功中斷了的:

這種開關的方式看起來包治百病,但是當遇到線程阻塞時,就會很無奈了,正如下面代碼所示:

public class InterruptionInJava implements Runnable{    private volatile static boolean on = false;    public static void main(String[] args) throws InterruptedException {        Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");        //start thread        testThread.start();        Thread.sleep(1000);        InterruptionInJava.on = true;        System.out.println("main end");    }    @Override    public void run() {        while(!on){            try {                Thread.sleep(10000000);            } catch (InterruptedException e) {                System.out.println("caught exception: "+e);            }        }    }}

線程被阻塞無法被中斷。這時候救世主interrupt函數又回來了,它可以迅速中斷被阻塞的線程,拋出一個InterruptedException,把線程從阻塞狀態中解救出來,show the code。

public class InterruptionInJava implements Runnable{    private volatile static boolean on = false;    public static void main(String[] args) throws InterruptedException {        Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");        //start thread        testThread.start();        Thread.sleep(1000);        InterruptionInJava.on = true;        testThread.interrupt();        System.out.println("main end");    }    @Override    public void run() {        while(!on){            try {                Thread.sleep(10000000);            } catch (InterruptedException e) {                System.out.println("caught exception right now: "+e);            }        }    }}

結果,達到預期。

這種情形同樣適用io阻塞,通常io阻塞會立即拋出一個SocketException,類似於上面說的InterruptedException。

 

java中interrupt的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.