interruptedexception(为什么会出现java.lang.InterruptedException)

本文目录
为什么会出现java.lang.InterruptedException
一般是线程在执行的时候被强行中断了。
在线程的执行过过程中,一个线程在休眠中,另一个线程调用了这个线程的Interrupt()方法,例如:
public class Test1 {
public static void main(String args) {
A a = new A();
a.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.interrupt();
}
static class A extends Thread{
public void run(){
try {
System.out.println("开始休眠");
Thread.sleep(40000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
如何处理InterruptedException异常
Interrupted Exception
中断故障(异常)
interrupted
adj.中断的; 被遮断的; 被阻止的; 不通的;
v.中断; 阻断; 打断( interrupt的过去式和过去分词 ); 暂停;
exception
n.例外,除外; 反对,批评; 异议,反对;
复数:exceptions
例句
The exception that is thrown when a thread is interrupted while it is in awaiting state.
当线程在处于等待状态的情况下被中断时引发的异常。
InterruptedException 是什么异常
InterruptedException异常为恢复中断
抛InterruptedException的代表方法有:
1. java.lang.Object 类的 wait 方法
2. java.lang.Thread 类的 sleep 方法
3. java.lang.Thread 类的 join 方法
特点:当一个方法后面声明可能会抛出InterruptedException 异常时,说明该方法是会花一点时间,但是可以取消的方法。
需要花点时间
wait
执行wait方法的线程,会进入等待区,等待被notify/notify All。在等待期间,线程不会活动。
sleep
执行sleep方法的线程,会暂停执行参数内所设置的时间。
sleep
执行join方法的线程,会等待到指定的线程结束为止。
可以取消
主要是通过interrupt方法来取消,并抛出InterruptedException异常。
interrupt方法是Thread类的实例方法,在执行的时候并不需要获取Thread实例的锁定,任何线程在任何时刻,都可以通过线程实例来调用其他线程的interrupt方法。
sleep
当在sleep中的线程被调用interrupt方法时,就会放弃暂停的状态,并抛出InterruptedException异常,这样一来,线程的控制权就交给了捕捉这个异常的catch块了。
wait
当线程调用wait方法后,线程在进入等待区时,会把锁定接触。当对wait中的线程调用interrupt方法时,会先重新获取锁定,再抛出InterruptedException异常,获取锁定之前,无法抛出InterruptedException异常。
join
当线程以join方法等待其他线程结束时,一样可以使用interrupt方法取消。因为join方法不需要获取锁定,故而与sleep一样,会马上跳到catch程序块。
interrupt方法的本质
interrupt方法其实只是改变了中断状态而已,InterruptedException是由wait、sleep等自个儿抛出的。
sleep、wait和join这些方法的内部会不断的检查中断状态的值,从而自己抛出InterruptedException。
备注:
isInterrupted方法,可以用来检查中断状态
Thread.interrupted方法,可以用来检查并清除中断状态。

更多文章:
false是精确匹配吗(vlookup 函数中的精确匹配和大致匹配的区别)
2026年10月12日 00:50
sumproduct多条件排名不重复(Excel 求助,如何多条件统计不重复个数)
2026年10月11日 23:10
gcc编译器参数(深度linux的arm-linux-gnueabihf-gcc编译参数如何配)
2026年10月11日 19:30
asp是什么检查项目(医院血液检验项目RPR、TPPA、HIV-Ab各是什么意思)
2026年10月11日 10:20
汇编输出指令(用汇编语言循环指令在屏幕中间输出红底白字的“hello I am 720“)
2026年10月11日 07:20
本地搭建springboot项目(使用eclipse构建springboot项目)
2026年10月11日 06:20





