Thread类中的interrupt()、interrupted()及isInterrupted()方法的区别
2024-01-26 18:50:28
本文将深入探讨Java Thread
类中的三个方法:interrupt()
、interrupted()
和 isInterrupted()
。这些方法对于了解线程的中断机制至关重要。
interrupt()
interrupt()
方法用于向正在运行的线程发送中断信号。当线程收到中断信号时,它会抛出 InterruptedException
异常。如果线程正在执行一个可能很长时间才能完成的任务,那么 interrupt()
方法可以用来打断这个任务。
例如,以下代码演示了如何使用 interrupt()
方法来中断一个正在运行的线程:
public class InterruptExample {
public static void main(String[] args) {
// 创建一个线程
Thread thread = new Thread(() -> {
// 执行一个可能很长时间才能完成的任务
while (true) {
System.out.println("I'm running...");
}
});
// 启动线程
thread.start();
// 等待一秒钟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 向线程发送中断信号
thread.interrupt();
// 等待线程终止
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread interrupted.");
}
}
interrupted()
interrupted()
方法用于检查当前线程是否收到了中断信号。如果当前线程收到了中断信号,那么 interrupted()
方法返回 true
,否则返回 false
。
例如,以下代码演示了如何使用 interrupted()
方法来检查当前线程是否收到了中断信号:
public class InterruptedExample {
public static void main(String[] args) {
// 创建一个线程
Thread thread = new Thread(() -> {
// 检查当前线程是否收到了中断信号
while (!Thread.interrupted()) {
System.out.println("I'm running...");
}
});
// 启动线程
thread.start();
// 等待一秒钟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 向线程发送中断信号
thread.interrupt();
// 等待线程终止
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread interrupted.");
}
}
isInterrupted()
isInterrupted()
方法与 interrupted()
方法类似,但它不会清除中断标志。这意味着,如果线程收到了中断信号,那么 isInterrupted()
方法总是返回 true
,即使中断信号已经被清除。
例如,以下代码演示了如何使用 isInterrupted()
方法来检查当前线程是否收到了中断信号:
public class IsInterruptedExample {
public static void main(String[] args) {
// 创建一个线程
Thread thread = new Thread(() -> {
// 检查当前线程是否收到了中断信号
while (!Thread.currentThread().isInterrupted()) {
System.out.println("I'm running...");
}
});
// 启动线程
thread.start();
// 等待一秒钟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 向线程发送中断信号
thread.interrupt();
// 等待线程终止
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread interrupted.");
}
}
总结
interrupt()
、interrupted()
和 isInterrupted()
是 Java Thread
类中的三个重要方法,它们用于控制线程的中断。interrupt()
方法用于向线程发送中断信号,interrupted()
方法用于检查当前线程是否收到了中断信号,isInterrupted()
方法用于检查当前线程是否收到了中断信号并且中断信号还没有被清除。