java多线程应用: getting thread blocked time

标签 java multithreading

我在工作线程结束之前调用 threadInfo.getBlockedCount()getBlockedTime()。 我的阻塞计数为 1,但阻塞时间为 0。 这是否意味着线程被阻塞,但阻塞时间小于一毫秒?

如果上述情况属实,是否有另一种方法可以获取线程被阻塞的准确时间?

最佳答案

但是,如果在 * 启动线程之前 * 调用 ThreadMXBean#setThreadContentionMonitoringEnabled(true),线程的阻塞时间(被阻塞)似乎只会返回非零结果。否则,它将始终返回零(如果禁用争用监控,则返回 -1)。下面的代码对此进行了演示:

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class BlockedTimeMain {
    public static void main(String[] _) throws InterruptedException  {
        ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
        final Object lock = new Object();

        Thread t = new Thread("Foo") {
            @Override public void run() {
                // This will block forever
                synchronized(lock) {
                    // Will never get here
                    System.out.println("Got the lock from " + Thread.currentThread());
                }
            }
        };
        synchronized(lock) {
            t.start();
            mbean.setThreadContentionMonitoringEnabled(true);
            for (int i=0; i < 5; i++) {
                ThreadInfo[] tis = mbean.getThreadInfo(new long[]{t.getId()}, true, true);
                ThreadInfo ti = tis[0];

                if (ti.getThreadId() != t.getId())
                    throw new AssertionError("Unexpected " + t.getId() + " vs " + tis[0].getThreadId());

                System.out.println(t + " " + ti.getThreadState() 
                        + ": blockedTime=" + ti.getBlockedTime() + "/" + ti.getBlockedCount() 
                        + ", waitTime" + ti.getWaitedTime() + "/" + ti.getWaitedCount());
                Thread.sleep(1000);
            }
        }
        System.exit(0);
    }
}

示例输出:

Thread[Foo,5,main] BLOCKED: blockedTime=0/1, waitTime0/0
Thread[Foo,5,main] BLOCKED: blockedTime=0/1, waitTime0/0
Thread[Foo,5,main] BLOCKED: blockedTime=0/1, waitTime0/0
Thread[Foo,5,main] BLOCKED: blockedTime=0/1, waitTime0/0

关于java多线程应用: getting thread blocked time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5400839/

相关文章:

java - 对实例变量、创建新对象和方法感到困惑吗?

java - 在 IDEA Scratch 文件中导入快捷方式

java - Python 缺少的 Java 标准库是什么?

java - ArrayList<String> 使用改造 android 解析为 recyclerview

Javax 验证不适用于值为数组或列表的 Hashmap

python - 阻止 pygtk GUI 在长时间运行的过程中锁定

android - 自定义异步任务的实现不起作用

java - 如何在调用 Join() 之前停止线程返回

java - 一些线程卡在 semaphore.aquire() (threads/semaphore/countdownlatch)

c++ - 日志记录和多线程