Java list of waiting threads

前端 未结 3 1101
忘掉有多难
忘掉有多难 2021-02-15 12:43

Is there a way to get a list of waiting threads/number of waiting threads on an object?

3条回答
  •  终归单人心
    2021-02-15 13:02

    You can use the JMX classes to inspect the threads:

    ThreadInfo[] infos = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true);
    

    Each blocked thread has a non null LockInfo associated that will let you identify on what object it's waiting:

    for (ThreadInfo info : infos) {
        LockInfo lockInfo = info.getLockInfo();
        if (lockInfo != null 
                && lockInfo.getClassName().equals(lock.getClass().getName()) 
                && lockInfo.getIdentityHashCode() == System.identityHashCode(lock)) {
    
            System.out.println("Thread waiting on " + lock + " : " + info.getThreadName());
        }
    }
    

提交回复
热议问题