Java 線程的停止

來源:互聯網
上載者:User

 </br>

 

class Student implements Runnable{public boolean flag=true;/*public void run() {while(flag){System.out.println(Thread.currentThread().getName());}}*/public synchronized void run(){while(flag){try {  wait();System.out.println(Thread.currentThread().getName());}catch(Exception ex){System.out.println(Thread.currentThread().getName()+".......Exception");flag=false;}}}}public class StopThread {public static void main(String args[]){Student stu=new Student();Thread t1=new Thread (stu);Thread t2=new Thread(stu);t1.start();t2.start();for(int i=0;i<100;i++){System.out.println(Thread.currentThread().getName());stu.flag=false;t1.interrupt();t2.interrupt();}}}/* * 線程的停止 *  在多線程中,線程一般都是迴圈執行的,而線程裡面執行的代碼就是run 方法裡面定義的代碼,如果run 函數運行結束,那麼線程自然結束 *  所以控制線程結束,就是控制run 方法裡面的迴圈結束,也就是在某一個時刻設定線程啟動並執行開關 *   *   *  而線上程出於wait 狀態下,你儘管改變了狀態,但現在處於wait 狀態,所有該現在就不能結束,那麼要用線程裡面的另一個方法: interrupt, *  interrupt 將清除wait sleep 的狀態,接著運行程式,同時會拋出一個InterruptException ,所以可以在catch捕捉的異常裡面設定 運行開關,而 *  這種方法如果裡面沒有wait,將不會停止線程 *   *  所以由上面兩點得出,要終止現在得有兩點,一是在某一時刻,設定線程的運行開關,而且如果有wait 的話,那麼就用interrupt ,然後捕捉異常,在異常 *  裡面設定 線程運行開關 *   * 2011/10/24  20:49:21 * */

聯繫我們

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