我在工作线程结束之前调用 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/