package com.wistron.swpc.ecs.util; public class WrongWayStopThread extends Thread{ public static void main(String[] args) { WrongWayStopThread thread = new WrongWayStopThread(); System.out.println("Starting thread..."); thread.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Interrupting thread... "); thread.interrupt(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Stopping application..."); } public void run(){ while(!this.isInterrupted()){ System.out.println("Thread is running..."); //下面幾行代碼是模擬Thread.sleep(1000),至於爲啥不用sleep是由於用了sleep沒法正確中斷線程 long time = System.currentTimeMillis(); while(System.currentTimeMillis()-time < 1000){ //減小屏幕輸出的空循環 } } } }
運行結果:java
Starting thread...
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Interrupting thread...
Stopping application...
上面模擬的sleep的方法換成sleepapp
package com.wistron.swpc.ecs.util; public class WrongWayStopThread extends Thread{ public static void main(String[] args) { WrongWayStopThread thread = new WrongWayStopThread(); System.out.println("Starting thread..."); thread.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Interrupting thread... "); thread.interrupt(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Stopping application..."); } public void run(){ while(!this.isInterrupted()){ System.out.println("Thread is running..."); //下面幾行代碼是模擬Thread.sleep(1000),至於爲啥不用sleep是由於用了sleep沒法正確中斷線程 /*long time = System.currentTimeMillis(); while(System.currentTimeMillis()-time < 1000){ //減小屏幕輸出的空循環 }*/ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
運行結果:this
Starting thread... Thread is running... Thread is running... Thread is running... Interrupting thread... java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.wistron.swpc.ecs.util.WrongWayStopThread.run(WrongWayStopThread.java:39) Thread is running... Thread is running... Thread is running... Thread is running... Stopping application... Thread is running... Thread is running... Thread is running... Thread is running... Thread is running...
換成sleep以後不能結束線程spa