推荐答案
在 Java 中,interrupt()、interrupted() 和 isInterrupted() 都是与线程中断相关的方法,但它们的作用和使用场景有所不同:
interrupt(): 用于中断目标线程。调用此方法会将目标线程的中断状态设置为true,如果目标线程正在阻塞状态(如sleep()、wait()、join()等),则会抛出InterruptedException,并清除中断状态。interrupted(): 这是一个静态方法,用于检查当前线程是否被中断,并清除中断状态。如果当前线程的中断状态为true,则返回true,并将中断状态重置为false。isInterrupted(): 这是一个实例方法,用于检查调用该方法的线程是否被中断,但不会清除中断状态。如果线程的中断状态为true,则返回true,否则返回false。
本题详细解读
interrupt()
interrupt() 方法是 Thread 类的一个实例方法,用于中断目标线程。调用此方法会将目标线程的中断状态设置为 true。如果目标线程正在执行 sleep()、wait()、join() 等阻塞操作,那么这些方法会抛出 InterruptedException,并且中断状态会被清除(即设置为 false)。
// www.javascriptcn.com code example
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted!");
}
});
thread.start();
thread.interrupt(); // 中断线程interrupted()
interrupted() 是 Thread 类的一个静态方法,用于检查当前线程是否被中断,并清除中断状态。如果当前线程的中断状态为 true,则返回 true,并将中断状态重置为 false。
Thread.currentThread().interrupt();
if (Thread.interrupted()) {
System.out.println("Thread was interrupted, and status is cleared.");
}isInterrupted()
isInterrupted() 是 Thread 类的一个实例方法,用于检查调用该方法的线程是否被中断,但不会清除中断状态。如果线程的中断状态为 true,则返回 true,否则返回 false。
// www.javascriptcn.com code example
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 线程继续执行
}
System.out.println("Thread was interrupted!");
});
thread.start();
thread.interrupt(); // 中断线程总结
interrupt()用于中断线程,可能会抛出InterruptedException。interrupted()是静态方法,检查并清除当前线程的中断状态。isInterrupted()是实例方法,检查线程的中断状态,但不会清除中断状态。