线程在park、sleep、wait情况下响应中断

如下这段代码演示了一个使用 Unsafe 类的 park 方法和普通的 sleep 方法来阻塞线程,并测试线程在不同阻塞状态下对中断的响应情况。

  1. 在 main 方法中,首先创建了一个新的线程 blockerThread,该线程会执行 runThread 方法中定义的逻辑。
  2. blockerThread 线程内部先调用 unsafe.park(false, 0) 方法来阻塞线程。park 方法会挂起当前线程,等待被唤醒。这里测试了使用 park 方法阻塞的线程如何响应中断:可以响应中断,且不会抛出异常。
  3. 紧接着,在主线程中通过 blockerThread.interrupt() 方法尝试中断 blockerThread 线程,观察其响应。然后等待一段时间。
  4. 再次调用 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 异常。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进窄门见微光行远路

如果对你有比较大的帮助

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值