在多线程编程中,线程中断是一个重要的概念。线程中断意味着线程的执行被外部事件打断,它通常用于通知线程需要停止当前操作。以下将详细解析五种常见导致线程中断的场景。
场景一:用户请求中断
当用户希望线程停止执行时,可以通过调用Thread.interrupt()方法来请求中断。这是最直接的中断线程的方式。
代码示例
public class UserInterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
// 模拟长时间运行的任务
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
});
thread.start();
// 请求中断线程
thread.interrupt();
}
}
在这个例子中,线程在执行Thread.sleep(10000)时被中断,捕获到InterruptedException并输出相应的信息。
场景二:线程等待同步监视器
当一个线程在等待获取同步监视器时,如果此时监视器被其他线程中断,等待的线程会抛出InterruptedException。
代码示例
public class SynchronizedInterruptExample {
public static void main(String[] args) {
Object lock = new Object();
Thread thread = new Thread(() -> {
synchronized (lock) {
try {
// 模拟长时间等待
lock.wait(10000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted while waiting.");
}
}
});
thread.start();
// 中断等待线程
thread.interrupt();
}
}
在这个例子中,线程在等待同步监视器时被中断,捕获到InterruptedException并输出相应的信息。
场景三:线程调用Object.wait()
当线程调用Object.wait()方法时,如果当前线程被中断,则会抛出InterruptedException。
代码示例
public class WaitInterruptExample {
public static void main(String[] args) {
Object lock = new Object();
Thread thread = new Thread(() -> {
synchronized (lock) {
try {
// 模拟长时间等待
lock.wait(10000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted while waiting.");
}
}
});
thread.start();
// 中断等待线程
thread.interrupt();
}
}
这个例子与场景二类似,线程在等待时被中断。
场景四:线程调用Thread.join()
当一个线程调用另一个线程的join()方法时,如果被加入的线程被中断,当前线程会抛出InterruptedException。
代码示例
public class JoinInterruptExample {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
// 模拟长时间运行的任务
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
});
thread.start();
// 等待线程结束
thread.join();
// 中断线程
thread.interrupt();
}
}
在这个例子中,主线程等待子线程结束,然后中断子线程。
场景五:线程调用Thread.sleep()
当线程调用Thread.sleep()方法时,如果当前线程被中断,则会抛出InterruptedException。
代码示例
public class SleepInterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
// 模拟长时间运行的任务
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
});
thread.start();
// 中断线程
thread.interrupt();
}
}
这个例子展示了线程在睡眠时被中断的情况。
总结来说,线程中断是Java多线程编程中的一个重要概念。了解并掌握线程中断的常见场景对于编写高效、稳定的并发程序至关重要。
