1.中断原理
java中断并非直接中断线程的运行,中断只是一种协作机制,每个线程底层都保留一个中断标志符,程序可以调用中断方法,但是是否真正的中断还是依赖于应用程序本身的处理,中断有对应2种情况,在线程阻塞时,对于某些特别的阻塞,例如Thread方法的sleep,Object的wait方法,以及一些nio的阻塞,阻塞队列的take方法等,如果在阻塞的状态下调用interrupt()方法,会导致抛出InterruptedException异常,并重置其中断状态,即为false。而在另一些常规的IO阻塞和同步阻塞,设置中断,都只会改变其中断状态,程序可以处理,也可以不处理。
下面的三个方法都是Thread类的。
中断相关方法 | 作用 |
---|---|
interrupt() | 设置线程中断的唯一方法 |
interrupted() | 静态方法,获取当前线程是否中断的方法,获取之后中断状态将会被重置,例如调用interrupt()方法,再调用interrupted()方法会返回true,第二次调用会返回false,因为中断的状态被重置了。 |
isInterrupted() | 返回线程的中断状态,中断不会被此方法改变。 |
2.实例
package com.thread.study;
import com.util.GeneryUtil;
public class InterruptTest implements Runnable{
@Override
public void run() {
try {
while(true) {
}
} catch (Exception e) {
GeneryUtil.outputConsole("interrupt Exception");
}
}
public static class InterruptTest2 implements Runnable{
@Override
public void run() {
System.out.println("this is InterruptTest2");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("InterruptedException of InterruptTest2");
e.printStackTrace();
}
}
}
public static class InterruptTest3 implements Runnable{
@Override
public void run() {
System.out.println("this is InterruptTest3");
synchronized (this){
try {
this.wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException of InterruptTest3");
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new InterruptTest());
Thread t2 = new Thread(new InterruptTest2());
Thread t3 = new Thread(new InterruptTest3());
t1.start();
t2.start();
t3.start();
Thread.sleep(3000);
Thread.currentThread().interrupt();
t2.interrupt();
t3.interrupt();
System.out.println("first get interrupt of status of t1:"+Thread.currentThread().interrupted());
System.out.println("second get interrupt of status of t1:"+Thread.currentThread().interrupted());
System.out.println("second get interrupt of status of t1 by isInterrupted's method "+Thread.currentThread().isInterrupted());
}
}