int nThreads = Thread.activeCount(); Thread ret[] = new Thread[nThreads];
Thread.enumerate(ret);
return ret;
}
/** * Helper function to access a thread per name (ignoring case) * * @param name * @return */ publicstatic Thread fetchThread(String name) { Thread[] threadArray = listThreads(); // for (Thread t : threadArray) for (int i = 0; i < threadArray.length; i++) { Thread t = threadArray[i]; if (t.getName().equalsIgnoreCase(name)) return t; } returnnull; }
/** * Allow for killing threads * * @param threadName * @param isStarredExp * (regular expressions with *) */ @SuppressWarnings("deprecation") publicstaticintkill(String threadName, boolean isStarredExp) { String me = "ThreadExplorer.kill: "; if (logger.isDebugEnabled()) { logger.debug("Entering " + me + " with " + threadName + " isStarred: " + isStarredExp); } int ret = 0; Pattern mypattern = null; if (isStarredExp) { String realreg = threadName.toLowerCase().replaceAll("\\*", "\\.\\*"); mypattern = Pattern.compile(realreg);
} Thread[] threads = listThreads(); for (int i = 0; i < threads.length; i++) { Thread thread = threads[i]; if (thread == null) continue; // kill the thread unless it is not current thread boolean matches = false;
if (isStarredExp) { Matcher matcher = mypattern.matcher(thread.getName().toLowerCase()); matches = matcher.matches(); } else { matches = (thread.getName().equalsIgnoreCase(threadName)); } if (matches && (Thread.currentThread() != thread) && !thread.getName().equals("main")) { if (logger.isInfoEnabled()) logger.info("Killing thread named [" + thread.getName() + "]"); // , removing its uncaught
Kill thread 开始前线程##### * [main] Group: main * [pool-1-thread-1] Group: main * [pool-1-thread-2] Group: main * [pool-1-thread-3] Group: main * [pool-1-thread-4] Group: main * [pool-1-thread-5] Group: main * [pool-1-thread-6] Group: main * [pool-1-thread-7] Group: main * [pool-1-thread-8] Group: main * [pool-1-thread-9] Group: main * [pool-1-thread-10] Group: main
Killing thread named [pool-1-thread-1] Killing thread named [pool-1-thread-3] Kill thread 结束后剩余线程##### * [main] Group: main * [pool-1-thread-2] Group: main * [pool-1-thread-4] Group: main * [pool-1-thread-5] Group: main * [pool-1-thread-6] Group: main * [pool-1-thread-7] Group: main * [pool-1-thread-8] Group: main * [pool-1-thread-9] Group: main * [pool-1-thread-10] Group: main