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