標籤: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-將多線程停止的兩種方法