如下这段代码演示了一个使用 Unsafe 类的 park 方法和普通的 sleep 方法来阻塞线程,并测试线程在不同阻塞状态下对中断的响应情况。
- 在
main
方法中,首先创建了一个新的线程blockerThread
,该线程会执行runThread
方法中定义的逻辑。 blockerThread
线程内部先调用unsafe.park(false, 0)
方法来阻塞线程。park
方法会挂起当前线程,等待被唤醒。这里测试了使用park
方法阻塞的线程如何响应中断:可以响应中断,且不会抛出异常。- 紧接着,在主线程中通过
blockerThread.interrupt()
方法尝试中断blockerThread
线程,观察其响应。然后等待一段时间。 - 再次调用
blockerThread.interrupt()
方法,这次是在sleep
阻塞状态下的线程。由于sleep
方法本身就会响应中断并抛出InterruptedException
异常,所以这里会捕获到异常并处理。
总体来说,这段代码主要展示了不同阻塞状态下线程对中断的响应情况:park
方法下的线程可以响应中断而不抛出异常,而 sleep
方法下的线程会抛出 InterruptedException
异常。这有助于理解 Java 中线程的阻塞与中断机制。希望这能帮助你理解这段代码!如果有任何疑问,请随时提出。
public class ParkInterruptExample {
private static final Unsafe unsafe;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe) f.get(null);
} catch (Exception ex) {
throw new Error(ex);
}
}
public static void main(String[] args) {
Thread blockerThread = runThread();
// 等待一段时间后中断阻塞中的线程
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
System.out.println("Main thread: Interrupting the blocker thread");
blockerThread.interrupt(); // 中断park阻塞中的线程,测试park状态的线程是否可以响应中断
System.out.println(System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
blockerThread.interrupt(); // 中断sleep中的线程,测试抛出异常
}
private static Thread runThread() {
Thread blockerThread = new Thread(() -> {
System.out.println("Blocker thread: Going to park...");
unsafe.park(false, 0); // 阻塞当前线程
// park挂起状态的线程可响应中断,且不会抛出异常
System.out.println(System.currentTimeMillis());
System.out.println("Blocker thread: Woken up from park");
System.out.println("Blocker thread: Interrupted? " + Thread.currentThread().isInterrupted());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// sleep是响应中断并且抛出异常
System.out.println("sleep failed caught: " + e.getMessage());
throw new RuntimeException("sleep failed");
}
});
blockerThread.start();
return blockerThread;
}
}
当线程处于 wait 状态时,也可以测试线程对中断的响应情况。
private static Thread runThread2() {
Object lock = new Object();
Thread blockerThread = new Thread(() -> {
System.out.println("Blocker thread: Going to wait...");
synchronized (lock) {
try {
lock.wait(); // 等待在 lock 对象上
} catch (InterruptedException e) {
// wait 是响应中断并且抛出异常
System.out.println("wait failed caught: " + e.getMessage());
throw new RuntimeException("wait failed");
}
}
System.out.println("Blocker thread: Woken up from wait");
System.out.println("Blocker thread: Interrupted? " + Thread.currentThread().isInterrupted());
});
blockerThread.start();
return blockerThread;
}
在这个修改后的代码中,我们创建了一个对象 lock
作为等待的锁对象,并在线程中使用 synchronized
同步块和 wait
方法将线程置于等待状态。在 wait
状态下,线程同样可以响应中断,并抛出 InterruptedException
异常。