interrup()
interrup()并不能直接中断线程的运行,它可以理解为线程的一个状态信号,具体做出如何操作要看线程的具体代码。
一个简单的例子:
public class InterruptExp3 { private static class Mythread extends Thread{ private int num=1; @Override public void run() { while(num<100){ System.out.println(num++); try { sleep(1000); } catch (Exception e) { e.printStackTrace(); } } System.out.println("Thread end!"); } } public static void main(String[] args) { Thread thread1=new Mythread(); thread1.start(); thread1.interrupt(); } }
输出结果如下:
如果该线程处于阻塞、限期等待或者无限期等待状态时调用interrupt(),那么就会抛出 InterruptedException,虽然调用了interrupt(),但是线程未中断。因为线程未对interrupt信号做出处理。
然后再看一个对interrupt做出处理的例子:
//在上述类中再加入一个内部类,如下 private static class Mythread2 extends Thread{ @Override public void run() { int time=0; while(!interrupted()){ //TODO try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } time++; System.out.println(time+"s"); } System.out.println("Thread end!"); } } public static void main(String[] args) { Thread thread2=new Mythread2(); thread2.start(); thread2.interrupt(); }
输出结果如下:
上文中说到如果该线程处于阻塞、限期等待或者无限期等待状态时调用interrupt(),那么就会抛出 InterruptedException,但是它并没有中断线程,所以我们可以通过调用interrup()将线程从阻塞状态解救出来。如下:
public class InterruptExp2 implements Runnable{ private volatile static boolean on=true; @Override public void run() { while(InterruptExp2.on){ try { Thread.sleep(1000*1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("thread end"); } public static void main(String[] args) { Thread t1=new Thread(new InterruptExp2()); t1.start(); InterruptExp2.on=false; //while条件即使修改,线程仍处于阻塞状态,调用Interrup()可中断阻塞。 System.out.println("-----"); t1.interrupt(); } }
输出结果如下: