如何获取在对象上具有锁定的线程的详细信息 [英] How to get details of Thread which posses a Lock on the object

查看:45
本文介绍了如何获取在对象上具有锁定的线程的详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说一个线程正在Java中的同步函数中执行,而另一个线程想要访问相同的方法,但是它将不得不等到第一个线程完成. 第二个线程如何知道哪个线程在对象上具有锁. 我想打印第一个线程的详细信息,并可能打印第一个线程的起始位置.

Let us say that one Thread is executing inside a Synchronized Function in Java and another Thread wants to access the same method but it will have to wait till the first Thread completes. How can the second Thread know which Thread is having the Lock on the Object. I would want to print the details of the first Thread and possibly from where the first Thread was initiated.

推荐答案

这有点棘手,几乎是Tom Hawtin所写的,但是在dumpAllThreads中获取ThreadInfo时,您必须明确地请求监视器信息. 像这样:

It is a little tricky, almost what Tom Hawtin wrote, but you must explicity request the monitor info when getting the ThreadInfo in dumpAllThreads. Something like:

    Object lock = ...
    ThreadMXBean mx = ManagementFactory.getThreadMXBean();
    ThreadInfo[] allInfo = mx.dumpAllThreads(true, false);
    for (ThreadInfo threadInfo : allInfo) {
        MonitorInfo[] monitors = threadInfo.getLockedMonitors();
        for (MonitorInfo monitorInfo : monitors) {
            if (monitorInfo.getIdentityHashCode() == System.identityHashCode(lock)) {
                StackTraceElement[] stackTrace = threadInfo.getStackTrace();
                // use the the Information from threadInfo
            }
        }
    }

这篇关于如何获取在对象上具有锁定的线程的详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆