執行緒停止的三種方式
阿新 • • 發佈:2018-11-20
執行緒停止的三種方式
- 設定標記位,可以使執行緒正常退出
- 使用stop方法強制使執行緒退出,但是該方法不太安全所以已經被廢棄了
- 使用Thread類中的一個interrupt()可以中斷執行緒
設定標記位
class MyThread implements Runnable{ private boolean flag = true; @Override public void run() { int i = 1; while(flag){ try { Thread.sleep(1000); System.out.println("第"+i+"次執行,執行緒名稱為:"+Thread.currentThread().getName()); i++; } catch (InterruptedException e) { e.printStackTrace(); } } } public void setFlag(boolean flag){ this.flag = flag; } } public class ticket{ public static void main(String[] args) { MyThread mt = new MyThread(); Thread thread = new Thread(mt,"張一山"); thread.start(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } mt.setFlag(false); System.out.println("程式碼結束"); } }
使用stop()方法強制使執行緒退出
class MyThread implements Runnable{ private boolean flag = true; @Override public void run() { int i = 1; try { Thread.sleep(1000); System.out.println("第"+i+"次執行,執行緒名稱為:"+Thread.currentThread().getName()); i++; } catch (InterruptedException e) { e.printStackTrace(); } } } public class ticket{ public static void main(String[] args) { MyThread mt = new MyThread(); Thread thread = new Thread(mt,"張一山"); thread.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } thread.stop(); System.out.println("程式碼結束"); } }
使用Thread.interrupt()
- interrupt()方法只是將執行緒的狀態設定為中斷狀態而已,它不會中斷一個正在執行的執行緒
- 此方法只是給執行緒傳遞一箇中斷訊號
- 程式可以根據此訊號來判斷是否需要終止
- 當執行緒使用了wait,sleep,join方法導致主執行緒阻塞,則interrupt()方法會線上程中丟擲InterruptException中斷異常,走catch塊,並且將執行緒的中斷狀態由true變為false
class MyThread implements Runnable{ private boolean flag = true; @Override public void run() { int i = 1; while(flag){ try { Thread.sleep(1000); boolean bool = Thread.currentThread().isInterrupted(); if(bool){ System.out.println("非阻塞情況下執行該操作"+bool); break; } System.out.println("第"+i+"次執行,執行緒名稱為:"+Thread.currentThread().getName()); i++; } catch (InterruptedException e) { System.out.println("退出了"); boolean bool = Thread.currentThread().isInterrupted(); System.out.println(bool); return ; } } } public void setFlag(boolean flag){ this.flag = flag; } } public class ticket{ public static void main(String[] args)throws InterruptedException { MyThread mt = new MyThread(); Thread thread = new Thread(mt,"張一山"); thread.start(); Thread.sleep(3000); thread.interrupt(); System.out.println("程式碼結束"); } }