是否所有线程都在资源上等待相同的条件?如果是,则可以尝试替换
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); }}


