1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| * 获取当前Java进程的活动线程数 * @return */ public Map<String, Object> getThreadsTotal() { Map<String, Object> threadDataMap = new HashMap<String, Object>();
Integer currentThreadCount = 0; Integer currentThreadsBusy = 0;
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); List<ObjectName> threadPools = new ArrayList<ObjectName>(); try { threadPools.addAll(mbeanServer.queryNames(new ObjectName("*:type=ThreadPool,*"), null));
for (final ObjectName threadPool : threadPools) { currentThreadCount += (Integer) mbeanServer.getAttribute(threadPool, "currentThreadCount"); currentThreadsBusy += (Integer) mbeanServer.getAttribute(threadPool, "currentThreadsBusy");
} } catch (MalformedObjectNameException e) { logger.error("Get threads information error.", e); } catch (ReflectionException e) { logger.error("Reflecttion error", e); } catch (InstanceNotFoundException e) { logger.error("Instance not found error.", e); } catch (MBeanException e) { logger.error("Mean error", e); } catch (AttributeNotFoundException e) { logger.error("Could not get attribute", e); }
threadDataMap.put("currentThreadCount", currentThreadCount); threadDataMap.put("currentThreadsBusy", currentThreadsBusy);
return threadDataMap; }
|