[英]Getting all the threads waiting for an object before calling notifyAll
我有很多代碼,處理器很小,
當調用notifyAll
,有時會產生性能問題(100ms),所以我想知道當前等待對象被釋放的線程是什么。
synchronized (obj){
//do some stuff..
obj.notifyall();
}
我想在調用obj.notifyAll()
之前打印等待對象釋放的所有線程
是否所有線程都在資源上等待相同的條件? 如果是,那么你可以嘗試替換obj.notify()
而不是obj.notifyAll
雖然它確實不推薦。 AFAIK,沒有辦法“檢索”等待給定對象的所有線程的列表(盡管你可以以編程方式獲取進程的線程轉儲並查看線程,但我確信這不是你所擁有的心神)。 即使有,列出線程然后與他們做“某事”肯定會花費更多時間來notifyAll
。
此外,如果“處理器很小”,嘗試限制產生的線程數量,因為沒有相當數量的“真實”線程,創建太多線程通常是開銷。 這樣, notifyAll
就不會喚醒一堆線程。
這是一個小程序,它演示了內聯注釋的線程狀態信息的轉儲:
package net.sanjayts.test;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.concurrent.TimeUnit;
public class ThreadDumpTest {
public static void main(String[] args) throws Exception {
final Object lock = new Object();
for (int i = 0; i < 6; ++i) {
final int cnt = i;
new DaemonThread(new Runnable() {
@Override
public void run() {
try {
// If counter is even, try to acquire common lock and then
// sleep. If odd, sleep without trying to acquire the lock.
// This way, if we do a thread dump, we'll see threads in
// different states (TIMED_WAIT for those sleeping threads
// and BLOCKED for those waiting for the common "lock".
if (cnt % 2 == 0) {
synchronized (lock) {
TimeUnit.MINUTES.sleep(1); // sleep 1 min
}
} else {
TimeUnit.MINUTES.sleep(1); // sleep 1 min
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "mythread-" + cnt).start();
}
ThreadInfo[] infos = ManagementFactory.
getThreadMXBean().dumpAllThreads(true, true);
for (ThreadInfo info : infos) {
System.out.println(info);
System.out.println("===========================");
}
TimeUnit.SECONDS.sleep(2);
}
}
class DaemonThread extends Thread {
public DaemonThread(Runnable r, String name) {
super(r, name);
setDaemon(true);
}
}
您可以使用Thread.getAllStackTraces()並打印出所有正在等待的線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.