InterruptedException
当一个线程在被阻塞状态(如调用 Thread.sleep() 或 Object.wait() 方法)时,如果其他线程调用该被阻塞线程的 interrupt() 方法,那么被阻塞线程会被中断,并抛出 InterruptedException 异常。
package com.lf.java.basic.concurrent;
class MyRunnable implements Runnable {
@Override
public void run() {
try {
// 被阻塞的线程,调用sleep方法
Thread.sleep(5000);
} catch (InterruptedException e) {
// 被中断时会抛出InterruptedException异常
System.out.println("Thread was interrupted.");
// 可以选择终止线程的执行
// return;
}
System.out.println("被唤醒了处理Exception后可以自由选择做什么事");
System.out.println("Thread completed.");
}
}
public class InterruptedExceptionSample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
// 主线程休眠一段时间后,中断被阻塞的线程
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
Thread was interrupted.
被唤醒了处理Exception后可以自由选择做什么事
Thread completed.
1、被阻塞的线程处于阻塞状态,比如调用了 Thread.sleep() 或 Object.wait() 方法。
2、其他线程调用了被阻塞线程的 interrupt() 方法。
3、被阻塞线程会被唤醒,它会检查自己是否被中断,如果被中断,就会抛出 InterruptedException 异常。
4、此时,被阻塞线程可以选择如何处理这个异常,比如捕获异常并做相应的处理,或者继续向上层抛出异常。
注意:
中断是一种协作机制,它并不能直接终止一个线程的执行。被中断的线程需要在适当的时候检查自己是否被中断,并做出相应的响应。在处理 InterruptedException 时,可以选择终止线程的执行或采取其他合适的措施来处理中断。(存在不能被中断的阻塞 I/O 调用, 应该考虑选择可中断的调 =用)。
interrupted() 方法(静态方法)
public static boolean interrupted()
interrupted() 方法是一个静态方法,用于检测当前线程是否被中断,并且会清除中断状态。当一个线程被中断时,该线程的中断状态会被设置为 true。当你调用 interrupted() 方法时,它会返回当前线程的中断状态,并且同时将中断状态重置为 false。这意味着,如果连续多次调用 interrupted() 方法,只有第一次会返回 true,之后的调用将返回 false,除非线程又被重新中断。
public class InterruptedSample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
if (Thread.interrupted()) {
System.out.println("Thread is interrupted.");
} else {
System.out.println("Thread is not interrupted.");
}
}
});
thread.start();
// 主线程休眠一段时间后,中断被阻塞的线程
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
isInterrupted() 方法(实例方法)
public boolean isInterrupted()
isInterrupted() 方法是一个实例方法,用于检查当前线程的中断状态,但不会清除中断状态。当你调用 isInterrupted() 方法时,它会返回当前线程的中断状态,并且不会改变中断状态。因此,多次调用 isInterrupted() 方法会一直返回相同的中断状态,不会重置为 false。
public class IsInterruptedSample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread is interrupted.");
} else {
System.out.println("Thread is not interrupted.");
}
}
});
thread.start();
// 主线程休眠一段时间后,中断被阻塞的线程
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}