</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 * */