import javax.imageio.*; import java.awt.image.*; import java.awt.event.*; import java.awt.*; import java.security.NoSuchAlgorithmException; import java.security.MessageDigest; import java.lang.management.*; import java.lang.reflect.*; import java.net.*; import java.io.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.*; import java.util.concurrent.atomic.*; import java.util.concurrent.*; import java.util.regex.*; import java.util.List; import java.util.zip.*; import java.util.*; public class main { static Map idToThread; public static void main(String[] args) throws Exception { ThreadMXBean mx = ManagementFactory.getThreadMXBean(); // just for fun print("Total started thread count: " + mx.getTotalStartedThreadCount()); boolean cpuTimeSupported = mx.isThreadCpuTimeSupported(); print("CPU time supported: " + cpuTimeSupported); if (!cpuTimeSupported) fail("No CPU time info available on platform."); long[] threads = mx.getAllThreadIds(); long time = now(); List l = getAllThreads(); print((now()-time) + " ms for getAllThreads()"); print(l.size() + " threads"); idToThread = new TreeMap(); for (Thread t : l) idToThread.put(t.getId(), t); for (long id : threads) { long nano = mx.getThreadCpuTime(id); long ms = nano/1000000; Thread t = idToThread.get(id); if (t == null) print("? thread not found: " + id); else print("Thread " + quote(t.getName()) + ": CPU time = " + ms + " ms"); } } static List getAllThreads() { ThreadGroup rootGroup = Thread.currentThread().getThreadGroup(); ThreadGroup parentGroup; while ( ( parentGroup = rootGroup.getParent() ) != null ) rootGroup = parentGroup; Thread[] threads = new Thread[rootGroup.activeCount()]; int n; while ((n = rootGroup.enumerate(threads, true)) == threads.length) threads = new Thread[threads.length*2]; List l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(threads[i]); return l; } static String quote(String s) { if (s == null) return "null"; return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\""; } static String quote(long l) { return quote("" + l); } static long now_virtualTime; static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static void print() { System.out.println(); } static void print(Object o) { System.out.println(o); } static void print(long i) { System.out.println(i); } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } }