interrupt()方法是在运行的线程中进行对该线程打上中断标记,只是告诉线程是,这个线程能够被中断,可是不会去进行中断操做,线程会保持执行,直到线程的代码执行完毕为止。html
这个是线程方法:java
public class MyService extends Thread{ public void run() { super.run(); for(int i=0;i < 50000;i++) { System.out.println("是否被中断:"+this.isInterrupted()); if(this.isInterrupted()) { System.out.println("已是中止状态了"); break; } System.out.println("i="+ (i+1)); } System.out.println("我被输出"); } }
这个是主线程main方法:this
public class Run { public static void main(String[] args) { try { MyService thread =new MyService(); thread.start(); Thread.sleep(10); thread.interrupt(); System.out.println("是否中止1:"+ thread.interrupted()); System.out.println("是否中止2:"+ thread.interrupted()); System.out.println("end!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
下面是运行结果:线程
是否被中断:false i=253 是否被中断:true 是否中止1:false 是否中止2:false end! 已是中止状态了
因此要想真正的中断一个线程,须要进行判断方法boolean interrupted()进行判断。code
最后讲一下:htm
中断线程。若是线程在调用 Object
类的 wait()
、wait(long)
或 wait(long, int)
方法,或者该类的 join()
、join(long)
、join(long, int)
、sleep(long)
或 sleep(long, int)
方法blog
过程当中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException
get
进行提早进行结束此状态,并进行抛出InterruptedException异常。 it