java 中 synchronized 关键字本身不支持响应中断,若需实现可中断的同步等待,应使用 java.util.concurrent.locks.reentrantlock 并调用其 lockinterruptibly() 方法。该方法会在获取锁的过程中检测当前线程是否被中断,一旦检测到中断状态,便抛出 interruptedexception 异常,从而允许程序跳出阻塞状态并进行清理或重试。

ReentrantLock 如何替代 synchronized 实现同步
要替换内置锁,需要实例化一个 ReentrantLock 对象,并在访问共享资源前调用 lockInterruptibly()。由于该方法会抛出受检异常,必须将其包裹在 try-catch 块中。在 catch 块中处理中断逻辑后,务必在 finally 块中调用 unlock() 以确保锁被释放,防止死锁。

import java.util.concurrent.locks.ReentrantLock;
public class InterruptibleSync {
private final ReentrantLock lock = new ReentrantLock();
private int counter = 0;
public void increment() {
try {
// 尝试获取锁,若被中断则抛出异常
lock.lockInterruptibly();
try {
counter++;
System.out.println("Counter: " + counter);
} finally {
// 确保锁被释放
lock.unlock();
}
} catch (InterruptedException e) {
// 恢复中断状态
Thread.currentThread().interrupt();
System.err.println("Operation interrupted");
}
}
}
中断处理后的状态恢复策略
当 lockInterruptibly() 捕获到 InterruptedException 时,线程的中断状态通常会被清除。为了保持中断语义的正确性,必须在 catch 块中重新调用 Thread.currentThread().interrupt() 来恢复中断标志。这样,上层调用者才能感知到该线程曾被请求中断,从而决定是终止线程还是执行其他恢复操作。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.locks.ReentrantLock;
public class InterruptHandler {
private final ReentrantLock lock = new ReentrantLock();
public void processWithRetry() {
while (true) {
try {
lock.lockInterruptibly();
try {
// 执行临界区代码
System.out.println("Processing...");
break; // 成功获取锁并执行后退出循环
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
// 恢复中断状态,以便外层能感知
Thread.currentThread().interrupt();
// 可以选择记录日志或返回,这里选择重试
System.out.println("Interrupted, retrying...");
}
}
}
}
基于 lockInterruptibly() 抛出异常的特定问题
在使用 lockInterruptibly() 时,一个关键的具体问题是:如果线程在等待锁期间被中断,它不会像 synchronized 那样继续等待直到获得锁,而是立即停止等待并抛出异常。这意味着开发者不能假设 lockInterruptibly() 调用成功后资源一定处于一致状态,必须在进入临界区前检查前置条件,或在异常处理中回滚部分操作。


















