尝试在子线程中获取父线程持有锁

之前有面试官问过是否可以在子线程中获取父线程所持有的锁,我根据以前看过的 ReentrantLock 的源码分析, AQS 的队首节点中保存的是成功获取同步状态 state 的线程引用,与父子线程无关,所以是不可以的

今天来实际的测试一下


1. ReentrantLock 测试

/**
 * Author:  heatdeath
 * Date:    2018/7/15
 * Desc:
 */
public class GetLockInChildThreadDemo {
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        lock.lock();
        try {
            System.out.println(Thread.currentThread() + " i got the lock");
            new Thread(() -> {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread() + " I got the lock and going to sleep");
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread() + " I am waked up");
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
                    lock.unlock();
                }
            }).start();
            Thread.sleep(6000);
            System.out.println(Thread.currentThread() + " I am waked up");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            lock.unlock();
        }
    }

}

输出

Thread[main,5,main] i got the lock
Thread[main,5,main] I am waked up
Thread[Thread-0,5,main] I got the lock and going to sleep
Thread[Thread-0,5,main] I am waked up

这里写图片描述


2. synchronized 测试

/**
 * Author:  heatdeath
 * Date:    2018/7/15
 * Desc:
 */
public class GetLockInChildThreadDemo {

    public static void main(String[] args) {

        synchronized (GetLockInChildThreadDemo.class) {
            try {
                System.out.println(Thread.currentThread() + " i got the lock");

                new Thread(() -> {
                    synchronized (GetLockInChildThreadDemo.class) {
                        try {
                            System.out.println(Thread.currentThread() + " I got the lock and going to sleep");
                            Thread.sleep(5000);
                            System.out.println(Thread.currentThread() + " I am waked up");
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }
                }).start();

                Thread.sleep(6000);
                System.out.println(Thread.currentThread() + " I am waked up");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

    }
}

输出:

Thread[main,5,main] i got the lock
Thread[main,5,main] I am waked up
Thread[Thread-0,5,main] I got the lock and going to sleep
Thread[Thread-0,5,main] I am waked up

GetLockInChildThreadDemo.class 对象只有一个 moniter ,只有等待 main 线程执行到 moniterexit 指令时,子线程才能执行 moniterenter 获取锁

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Java中,每个线程都有自己的ThreadLocal变量副本,可以在不同的线程中访问ThreadLocal中的数据,而不会出现线程安全问题。如果在线程中需要获取ThreadLocal中的数据,可以通过以下两种方式来实现: 1. 将ThreadLocal对象传递给线程:在创建线程时,将主线程中的ThreadLocal对象作为参数传递给线程,在线程中就可以访问到主线程中的ThreadLocal对象,并获取其中的数据。 示例代码如下: ```java public class MyRunnable implements Runnable { private ThreadLocal<String> threadLocal; public MyRunnable(ThreadLocal<String> threadLocal) { this.threadLocal = threadLocal; } public void run() { String data = threadLocal.get(); // 在线程中获取ThreadLocal中的数据 // do something with data } } // 在主线程中创建ThreadLocal对象 ThreadLocal<String> threadLocal = new ThreadLocal<>(); threadLocal.set("data"); // 在主线程中创建线程,并将ThreadLocal对象传递给线程 Thread thread = new Thread(new MyRunnable(threadLocal)); thread.start(); ``` 2. 使用InheritableThreadLocal对象:InheritableThreadLocal对象是ThreadLocal的一个类,可以实现将ThreadLocal变量值从线程传递到线程中。 示例代码如下: ```java public class MyRunnable implements Runnable { private InheritableThreadLocal<String> threadLocal; public MyRunnable(InheritableThreadLocal<String> threadLocal) { this.threadLocal = threadLocal; } public void run() { String data = threadLocal.get(); // 在线程中获取ThreadLocal中的数据 // do something with data } } // 在主线程中创建InheritableThreadLocal对象 InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<>(); threadLocal.set("data"); // 在主线程中创建线程,线程可以继承ThreadLocal对象中的数据 Thread thread = new Thread(new MyRunnable(threadLocal)); thread.start(); ``` 需要注意的是,ThreadLocal中保存的数据只在当前线程中有效,如果需要在多个线程中共享数据,需要使用其他的方式来实现,例如使用静态变量、全局变量、单例模式、数据库、缓存、消息队列等方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值