015.3線程停止,015.3線程

來源:互聯網
上載者:User

015.3線程停止,015.3線程

其他線程wait,主線程執行完畢,程式不會退出。通過interrupt()方法強制弄醒
解決線程在主線程結束了,還在等待的情況

 1 //示範停止線程。 2 class Demo implements Runnable 3 { 4     private boolean flag = true; 5     public synchronized void run() 6     { 7         while(flag) 8         { 9             try10             {11                 wait();//t1  t212             }13             catch (InterruptedException e)14             {15                 System.out.println(Thread.currentThread().toString()+"....."+e.toString());16                 changeFlag();17             }18 19             System.out.println(Thread.currentThread().getName()+"----->");20         }21     }22     //對標記的修改方法。23     public void changeFlag()24     {25         flag = false;26     }27 }28 29 30 class StopThreadDemo 31 {32     public static void main(String[] args) 33     {34         Demo d = new Demo();35 36         Thread t1 = new Thread(d,"旺財");37         Thread t2 = new Thread(d,"小強");38         t1.start();39         //將t2標記為後台線程,守護線程。40 //        t2.setDaemon(true);41         t2.start();42 43         int x = 0;44         while(true)45         {46             if(++x == 50)//條件滿足。47             {48 //                d.changeFlag();//改變線程任務代碼的標記,讓其他線程也結束。49                 //對t1線程對象進行中斷狀態的清除,強制讓其恢複到運行狀態。50                 t1.interrupt();51                 //對t2線程對象進行中斷狀態的清除,強制讓其恢複到運行狀態。52                 t2.interrupt();53                 break;//跳出迴圈,主線程可以結束。54             }55             System.out.println("main-------->"+x);56         }57         System.out.println("over");58     }59 }

 

聯繫我們

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