在Java中,处理线程中断的方法如下:
Thread类或实现Runnable接口。在这两种情况下,都需要重写run()方法,该方法包含线程执行的代码。继承Thread类的示例:
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
}
}
实现Runnable接口的示例:
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
run()方法中,使用try-catch语句捕获InterruptedException异常。当线程被中断时,会抛出此异常。在catch块中,可以编写处理中断的逻辑,例如设置线程的中断状态为false,或者执行其他清理操作。继承Thread类的示例:
class MyThread extends Thread {
@Override
public void run() {
try {
// 线程执行的代码
} catch (InterruptedException e) {
// 处理中断的逻辑
Thread.currentThread().interrupt(); // 重新设置中断状态
}
}
}
实现Runnable接口的示例:
class MyRunnable implements Runnable {
@Override
public void run() {
try {
// 线程执行的代码
} catch (InterruptedException e) {
// 处理中断的逻辑
Thread.currentThread().interrupt(); // 重新设置中断状态
}
}
}
start()方法启动线程。如果需要检查线程是否已被中断,可以使用isInterrupted()方法。示例:
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
try {
Thread.sleep(1000); // 让新线程执行一段时间
} catch (InterruptedException e) {
e.printStackTrace();
}
if (myThread.isInterrupted()) {
System.out.println("线程已被中断");
} else {
System.out.println("线程未中断");
}
}
}
注意:在捕获InterruptedException异常后,建议重新设置线程的中断状态,以便其他代码或线程能够检测到中断。