LockSupport的park与unpark调用顺序验证

本文通过三个实验深入探讨了Java中LockSupport类的unpark和park方法的使用时机与效果,揭示了线程唤醒的机制。实验表明,unpark必须在线程启动后才能生效,无论是在park前还是后调用,都能成功唤醒线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.unpark在thread start之前调用

    public static void main(String[] args) throws InterruptedException{
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 start");

                try{
                    Thread.sleep(2000);
                } catch (Exception e){
                    e.printStackTrace();
                }

                System.out.println("thread1 run before park");

                LockSupport.park();

                System.out.println("thread1 run after park");
            }
        });
        LockSupport.unpark(thread1);
        thread1.start();

        System.out.println("main thread");

    }

执行结果:

main thread
thread1 start
thread1 run before park

(程序没有退出,线程1一直挂起)

2.unpark在park之前执行

public static void main(String[] args) throws InterruptedException{
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 start");

                try{
                    Thread.sleep(2000);
                } catch (Exception e){
                    e.printStackTrace();
                }

                System.out.println("thread1 run before park");

                LockSupport.park();

                System.out.println("thread1 run after park");
            }
        });
        thread1.start();
        LockSupport.unpark(thread1);

        System.out.println("main thread");

    }

执行结果:

thread1 start
main thread
thread1 run before park
thread1 run after park

3.unpark在park之后执行

    public static void main(String[] args) throws InterruptedException{
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 run before park");

                LockSupport.park();

                System.out.println("thread1 run after park");
            }
        });

        thread1.start();

        System.out.println("main thread");
        Thread.sleep(3000);
        LockSupport.unpark(thread1);
    }

执行结果:

main thread
thread1 run before park
thread1 run after park

总结

1.unpark必须在thread start之后才有用,之前调用没有任何效果;

2.thread start之后,unpark在park之前还是之后,作用是一样的,都会重新唤醒线程;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值