如果跑出异常,中断状态设置为false。
public class InterruptThread extends Thread {
@Override
public void run() {
while (true) {
}
}
public static void main(String[] args) throws InterruptedException {
InterruptThread thread = new InterruptThread();
thread.start();
System.out.println(thread.getState());
sleep(1000);
thread.interrupt();
System.out.println(thread.getState());
System.out.println(thread.isInterrupted());
}
}
运行结果如下
可以看出,虽然中断状态是true了,但是程序依然在运行,所以interrupt并没有强制中断线程。
public class InterruptThread2 extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
}
System.out.println("已中断");
}
public static void main(String[] args) throws InterruptedException {
InterruptThread2 thread = new InterruptThread2();
thread.start();
System.out.println(thread.getState());
sleep(1000);
thread.interrupt();
System.out.println(thread.getState());
System.out.println(thread.isInterrupted());
}
}
运行结果如下:
跟例子1的区别是,通过判断中断状态,来处理我们自己的业务逻辑,这样的设计,给程序带来了极大的利灵活性。
public class InterruptWait extends Thread {
@Override
public void run() {
waitFun();
}
public synchronized void waitFun(){
try {
wait();
} catch (InterruptedException e) {
System.out.println("打扰我等待了");
}
}
public static void main(String[] args) throws InterruptedException {
InterruptWait thread = new InterruptWait();
thread.start();
System.out.println(thread.getState());
sleep(1000);
thread.interrupt();
sleep(1000);
System.out.println(thread.getState());
System.out.println(thread.isInterrupted());
sleep(1000);
System.out.println(thread.getState());
}
}
运行结果如下:
中断wait方法,这里需要注意的是,抛出异常后,中断状态变成false。
public class InterruptWait extends Thread {
@Override
public void run() {
waitFun();
}
public synchronized void waitFun(){
try {
wait();
} catch (InterruptedException e) {
System.out.println("打扰我等待了");
}
}
public static void main(String[] args) throws InterruptedException {
InterruptWait thread = new InterruptWait();
thread.start();
System.out.println(thread.getState());
sleep(1000);
thread.interrupt();
sleep(1000);
System.out.println(thread.getState());
System.out.println(thread.isInterrupted());
sleep(1000);
System.out.println(thread.getState());
}
}
运行结果如下:
结果同上,抛出异常后,中断状态变成false。
public class InterruptSync extends Thread {
@Override
public void run() {
syncFun();
}
public static synchronized void syncFun() {
while (true) {
}
}
public static void main(String[] args) throws InterruptedException {
InterruptSync thread = new InterruptSync();
InterruptSync thread2 = new InterruptSync();
thread.start();
sleep(1000);
thread2.start();
sleep(1000);
System.out.println(thread.getState());
System.out.println(thread2.getState());
thread2.interrupt();
sleep(1000);
System.out.println(thread2.getState());
System.out.println(thread2.isInterrupted());
}
}
运行结果如下:
没有抛异常,结果同例子1。