Java-將多線程停止的兩種方法

來源:互聯網
上載者:User

標籤:notify   標記   zed   解決方案   log   blog   rup   ble   --   

線程如何停止呢
stop方法過時了,看起描述發現,有其他解決方案。
線程結束:就是讓線程任務代碼執行完,run方法結束。
run方法怎麼結束呢?
run方法中通常都定義迴圈,只要控制住迴圈就哦了。

//示範停止線程。class Demo implements Runnable {    private boolean flag = true;    public void run() {        while(flag) {            System.out.println(Thread.currentThread().getName()+"----->");        }    }    //對標記的修改方法。    public void changeFlag() {        flag = false;    }}class  MStopThreadDemo {    public static void main(String[] args) {        Demo d = new Demo();        Thread t1 = new Thread(d);        Thread t2 = new Thread(d);        t1.start();        t2.start();        int x = 0;        while(true) {            if(++x == 50) {                d.changeFlag();//改變線程任務代碼的標記,讓其他線程也結束。                break;//跳出迴圈,主線程可以結束。            }            System.out.println("main-------->"+x);        }        System.out.println("over");    }}

 

注意:萬一線程在任務中處於了凍結狀態,那麼它還能去判斷標記嗎?不能!
怎麼辦?通過查閱stop方法的描述,發現提供了一個解決方案:
如果目標線程等待很長時間,則應使用 interrupt 方法來中斷該等待
所謂的中斷並不是停止線程。
interrupt的功能是 將線程的凍結狀態清除,讓線程恢複到的運行狀態(讓線程重新具備cpu的執行資格)。
因為是強制性的所以會有異常InterruptedException發生,可以在catch中捕獲異常,
在異常處理中,改變標記讓迴圈結束,讓run方法結束。

//示範停止線程。class Demo implements Runnable {    private boolean flag = true;    public synchronized void run() {//不要這麼做將synchronized加到run方法這已經變成了單線程了這裡是故意這麼做為了測試因為wait()必須要有所屬的鎖          while(flag) {            try {                wait();//t1  t2   //如果使用notify()必須和wait()在同一個鎖裡,那如果不在同一個鎖怎麼辦只能用interrupt()            }            catch (InterruptedException e) {                System.out.println(Thread.currentThread().toString()+"....."+e.toString());                changeFlag();  // 由於interrupt()方法是強制性讓線程恢複到運行狀態,既然是強制的就會拋出異常所以在異常捕獲時將他標記進行修改            }            System.out.println(Thread.currentThread().getName()+"----->");        }    }    //對標記的修改方法。    public void changeFlag() {        flag = false;    }}class MStopThreadDemo2 {    public static void main(String[] args) {        Demo d = new Demo();        Thread t1 = new Thread(d);        Thread t2 = new Thread(d);        t1.start();
     t2.start();
int x = 0; while(true){ if(++x == 50){ //d.changeFlag();//改變線程任務代碼的標記,讓其他線程也結束。 //對t1線程對象進行中斷狀態的清除,強制讓其恢複到運行狀態。 t1.interrupt(); //對t2線程對象進行中斷狀態的清除,強制讓其恢複到運行狀態。 t2.interrupt(); break;//跳出迴圈,主線程可以結束。 } System.out.println("main-------->"+x); } System.out.println("over"); }}

 

Java-將多線程停止的兩種方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.