`
bao231
  • 浏览: 85741 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

java 如何根据线程id找到线程

 
阅读更多
/**
 * Copyright 2008, David Robert Nadeau, NadeauSoftware.com
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 2 of
 * the License, or (at your option) any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this file.  If not, see
 * <a href="http://www.gnu.org/licenses">GNU Licenses</a>.
 */

import java.lang.management.*;

/**
 * The ThreadUtilities class provides a collection of static methods
 * for listing and finding Thread, ThreadGroup, and ThreadInfo objects.
 * <p>
 * Please see the accompanying article:
 * <a href="http://nadeausoftware.com/articles/2008/04/java_tip_how_list_and_find_threads_and_thread_groups">Java tip:  How to list and find threads and thread groups</a>
 *
 * @author	<a href="http://NadeauSoftware.com/">David R. Nadeau</a>
 */
public final class ThreadUtilities
{
// Dummy constructor
	/**
	 * The ThreadUtilities class cannot be instanced.
	 */
	private ThreadUtilities( )
	{
	}





// Thread groups
	/**
	 * The root thread group saved on the first search for it.
	 * The root group doesn't change for the life of the JVM,
	 * so once found there is no need to find it again.
	 */
	private static ThreadGroup rootThreadGroup = null;

	/**
	 * Get the root thread group in the thread group tree.
	 * Since there is always a root thread group, this
	 * method never returns null.
	 *
	 * @return		the root thread group
	 */
	public static ThreadGroup getRootThreadGroup( )
	{
		if ( rootThreadGroup != null )
			return rootThreadGroup;

		ThreadGroup tg = Thread.currentThread( ).getThreadGroup( );
		ThreadGroup ptg;
		while ( (ptg = tg.getParent( )) != null )
			tg = ptg;
		rootThreadGroup = tg;
		return tg;
	}

	/**
	 * Get a list of all thread groups.  Since there is
	 * always at least one thread group (the root), this
	 * method never returns a null or empty array.
	 *
	 * @return		an array of thread groups
	 */
	public static ThreadGroup[] getAllThreadGroups( )
	{
		final ThreadGroup root = getRootThreadGroup( );
		int nAlloc = root.activeGroupCount( );
		int n = 0;
		ThreadGroup[] groups = null;
		do
		{
			nAlloc *= 2;
			groups = new ThreadGroup[ nAlloc ];
			n = root.enumerate( groups, true );
		} while ( n == nAlloc );
		ThreadGroup[] allGroups = new ThreadGroup[n+1];
		allGroups[0] = root;
		System.arraycopy( groups, 0, allGroups, 1, n );
		return allGroups;
	}

	/**
	 * Get the thread group with the given name.  A null is
	 * returned if no such group is found.  If more than one
	 * group has the same name, the first one found is returned.
	 *
	 * @param	name	the thread group name to search for
	 * @return		the thread group, or null if not found
	 * @throws	NullPointerException
	 * 			if the name is null
	 */
	public static ThreadGroup getThreadGroup( final String name )
	{
		if ( name == null )
			throw new NullPointerException( "Null name" );
		final ThreadGroup[] groups = getAllThreadGroups( );
		for ( ThreadGroup group : groups )
			if ( group.getName( ).equals( name ) )
				return group;
		return null;
	}





// Threads
	/**
	 * Get a list of all threads.  Since there is always at
	 * least one thread, this method never returns null or
	 * an empty array.
	 *
	 * @return		an array of threads
	 */
	public static Thread[] getAllThreads( )
	{
		final ThreadGroup root = getRootThreadGroup( );
		final ThreadMXBean thbean =
			ManagementFactory.getThreadMXBean( );
		int nAlloc = thbean.getThreadCount( );
		int n = 0;
		Thread[] threads = null;
		do
		{
			nAlloc *= 2;
			threads = new Thread[ nAlloc ];
			n = root.enumerate( threads, true );
		} while ( n == nAlloc );
		return java.util.Arrays.copyOf( threads, n );
	}

	/**
	 * Get a list of all threads in a thread group.  An empty
	 * array is returned if there are no threads in the group.
	 *
	 * @param	group	the thread group to list
	 * @return		an array of threads
	 * @throws	NullPointerException
	 * 			if the group is null
	 */
	public static Thread[] getGroupThreads( final ThreadGroup group )
	{
		if ( group == null )
			throw new NullPointerException( "Null group" );
		int nAlloc = group.activeCount( );
		int n = 0;
		Thread[] threads = null;
		do
		{
			nAlloc *= 2;
			threads = new Thread[ nAlloc ];
			n = group.enumerate( threads, false );
		} while ( n == nAlloc );
		return java.util.Arrays.copyOf( threads, n );
	}

	/**
	 * Get a list of all threads in a named thread group.
	 * A null is returned if the group cannot be found.
	 * An empty array is returned if there are no threads in
	 * the group.
	 *
	 * @param	name	the name of the thread group
	 * @return		an array of threads, or null if the
	 *			group is not found
	 * @throws	NullPointerException
	 * 			if the name is null
	 */
	public static Thread[] getGroupThreads( final String name )
	{
		final ThreadGroup group = getThreadGroup( name );
		if ( group == null )
			return null;
		return getGroupThreads( group );
	}

	/**
	 * Get a list of all threads, sorted from highest to
	 * lowest priority.  Since there is always at least one
	 * thread, this method never returns null or an empty
	 * array.  Since threads may change their priority during
	 * this method's sort, the returned thread list may not be
	 * correct by the time it is returned.
	 *
	 * @return		an array of threads
	 */
	public static Thread[] getAllThreadsPrioritized( )
	{
		final Thread[] allThreads = getAllThreads( );
		java.util.Arrays.sort( allThreads,
		new java.util.Comparator<Thread>( )
		{
			public int compare( final Thread t1, final Thread t2 )
			{ return t2.getPriority( ) - t1.getPriority( ); }
		} );
		return allThreads;
	}

	/**
	 * Get a list of all daemon threads.  An empty array is
	 * returned if there are no daemon threads.
	 *
	 * @return		an array of daemon threads
	 */
	public static Thread[] getAllDaemonThreads( )
	{
		final Thread[] allThreads = getAllThreads( );
		final Thread[] daemons = new Thread[allThreads.length];
		int nDaemon = 0;
		for ( Thread thread : allThreads )
			if ( thread.isDaemon( ) )
				daemons[nDaemon++] = thread;
		return java.util.Arrays.copyOf( daemons, nDaemon );
	}

	/**
	 * Get a list of all threads with a given thread state.
	 * Thread states are defined in the Thread.State enum for
	 * the Thread class.  Principal thread states include
	 * RUNNABLE, WAITING, TIMED_WAITING, and BLOCKED.  An
	 * empty array is returned if there are no threads in
	 * the chosen state.
	 *
	 * @param	state	the state to look for
	 * @return		an array of threads in that state
	 */
	public static Thread[] getAllThreads( final Thread.State state )
	{
		final Thread[] allThreads = getAllThreads( );
		final Thread[] found = new Thread[allThreads.length];
		int nFound = 0;
		for ( Thread thread : allThreads )
			if ( thread.getState( ) == state )
				found[nFound++] = thread;
		return java.util.Arrays.copyOf( found, nFound );
	}

	/**
	 * Get the thread with the given name.  A null is returned
	 * if no such thread is found.  If more than one thread has
	 * the same name, the first one found is returned.
	 *
	 * @param	name	the thread name to search for
	 * @return		the thread, or null if not found
	 * @throws	NullPointerException
	 * 			if the name is null
	 */
	public static Thread getThread( final String name )
	{
		if ( name == null )
			throw new NullPointerException( "Null name" );
		final Thread[] threads = getAllThreads( );
		for ( Thread thread : threads )
			if ( thread.getName( ).equals( name ) )
				return thread;
		return null;
	}

	/**
	 * Get the thread with the given ID.  A null is returned
	 * if no such thread is found.
	 *
	 * @param	id	the thread ID to search for
	 * @return		the thread, or null if not found
	 */
	public static Thread getThread( final long id )
	{
		final Thread[] threads = getAllThreads( );
		for ( Thread thread : threads )
			if ( thread.getId( ) == id )
				return thread;
		return null;
	}

	/**
	 * Get the thread for the given thread info.  A null
	 * is returned if the thread cannot be found.
	 *
	 * @param	info	the thread info to search for
	 * @return		the thread, or null if not found
	 * @throws	NullPointerException
	 * 			if info is null
	 */
	public static Thread getThread( final ThreadInfo info )
	{
		if ( info == null )
			throw new NullPointerException( "Null info" );
		return getThread( info.getThreadId( ) );
	}





// ThreadInfo
	/**
	 * Get a list of all thread info objects.  Since there is
	 * always at least one thread running, there is always at
	 * least one thread info object.  This method never returns
	 * a null or empty array.
	 *
	 * @return		an array of thread infos
	 */
	public static ThreadInfo[] getAllThreadInfos( )
	{
		final ThreadMXBean thbean =
			ManagementFactory.getThreadMXBean( );
		final long[] ids = thbean.getAllThreadIds( );

		// Get thread info with lock info, when available.
		ThreadInfo[] infos;
		if ( !thbean.isObjectMonitorUsageSupported( ) ||
			!thbean.isSynchronizerUsageSupported( ) )
			infos = thbean.getThreadInfo( ids );
		else
			infos = thbean.getThreadInfo( ids, true, true );

		// Clean nulls from array if threads have died.
		final ThreadInfo[] notNulls = new ThreadInfo[infos.length];
		int nNotNulls = 0;
		for ( ThreadInfo info : infos )
			if ( info != null )
				notNulls[nNotNulls++] = info;
		if ( nNotNulls == infos.length )
			return infos;	// Original had no nulls
		return java.util.Arrays.copyOf( notNulls, nNotNulls );
	}

	/**
	 * Get the thread info for the thread with the given name.
	 * A null is returned if no such thread info is found.
	 * If more than one thread has the same name, the thread
	 * info for the first one found is returned.
	 *
	 * @param	name	the thread name to search for
	 * @return		the thread info, or null if not found
	 * @throws	NullPointerException
	 * 			if the name is null
	 */
	public static ThreadInfo getThreadInfo( final String name )
	{
		if ( name == null )
			throw new NullPointerException( "Null name" );

		final Thread[] threads = getAllThreads( );
		for ( Thread thread : threads )
			if ( thread.getName( ).equals( name ) )
				return getThreadInfo( thread.getId( ) );
		return null;
	}

	/**
	 * Get the thread info for the thread with the given ID.
	 * A null is returned if no such thread info is found.
	 *
	 * @param	id	the thread ID to search for
	 * @return		the thread info, or null if not found
	 * @throws	IllegalArgumentException
	 *			if id <= 0
	 */
	public static ThreadInfo getThreadInfo( final long id )
	{
		final ThreadMXBean thbean =
			ManagementFactory.getThreadMXBean( );

		// Get thread info with lock info, when available.
		if ( !thbean.isObjectMonitorUsageSupported( ) ||
			!thbean.isSynchronizerUsageSupported( ) )
			return thbean.getThreadInfo( id );

		final ThreadInfo[] infos = thbean.getThreadInfo(
			new long[] { id }, true, true );
		if ( infos.length == 0 )
			return null;
		return infos[0];
	}

	/**
	 * Get the thread info for the given thread.  A null is
	 * returned if the thread info cannot be found.
	 *
	 * @param	thread	the thread to search for
	 * @return		the thread info, or null if not found
	 * @throws	NullPointerException
	 * 			if thread is null
	 */
	public static ThreadInfo getThreadInfo( final Thread thread )
	{
		if ( thread == null )
			throw new NullPointerException( "Null thread" );
		return getThreadInfo( thread.getId( ) );
	}





// MonitorInfo and LockInfo
	/**
	 * Get the thread holding a lock on the given object.
	 * A null is returned if there is no such thread.
	 *
	 * @param	object		the object to look for a lock on
	 * @return			the thread holding a lock, or
	 * 				null if there is none
	 * @throws	NullPointerException
	 * 				if the object is null
	 */
	public static Thread getLockingThread( final Object object )
	{
		if ( object == null )
			throw new NullPointerException( "Null object" );
		final long identity = System.identityHashCode( object );

		final Thread[] allThreads = getAllThreads( );
		ThreadInfo info = null;
		MonitorInfo[] monitors = null;
		for ( Thread thread : allThreads )
		{
			info = getThreadInfo( thread.getId( ) );
			if ( info == null )
				continue;
			monitors = info.getLockedMonitors( );
			for ( MonitorInfo monitor : monitors )
				if ( identity == monitor.getIdentityHashCode( ) )
					return thread;
		}
		return null;
	}

	/**
	 * Get the thread who's lock is blocking the given thread.
	 * A null is returned if there is no such thread.
	 *
	 * @param	blockedThread	the blocked thread
	 * @return			the blocking thread, or null if
	 * 				there is none
	 * @throws	NullPointerException
	 * 				if the blocked thread is null
	 */
	public static Thread getBlockingThread( final Thread blockedThread )
	{
		final ThreadInfo info = getThreadInfo( blockedThread );
		if ( info == null )
			return null;
		final long id = info.getLockOwnerId( );
		if ( id == -1 )
			return null;
		return getThread( id );
	}
} 

http://nadeausoftware.com/articles/2008/04/java_tip_how_list_and_find_threads_and_thread_groups 

0
1
分享到:
评论
2 楼 zijinSiShaojun 2018-02-12  
很不错的工具类。
很久了,不知道有没有更新
1 楼 chenxuezhou_yzl 2017-02-28  
11111111111

相关推荐

    java多线程查询数据库

    java多线程并发查询数据库,使用线程池控制分页,并发查询。

    JAVA线程停止的方法

    JAVA线程停止的方法

    java 多线程聊天系统

    QQ界面的聊天系统,服务器端用多线程实现了公共聊天和私人聊天,还可以传送简单的文本文档 说明: 主程序:SFace.java和Face.java 服务器端操作说明: 1、输入本地IP和聊天通信的端口,然后建立服务器; 2、消息...

    java的ftp多线程下载

    本程序是在原有基础上逐步完善的,第一版:...详细文档请看: http://www.open-open.com/home/space.php?uid=183&do=blog&id=8799 本程序很适合在主机间批量传输文件和目录,参数可控

    java多线程安全性基础介绍.pptx

    类似于一个以线程id为key的map 不可变对象状态 final 关键共享资源上互斥,变并发为串行即同步 锁 分类 显示锁 Lock Lock是个接口 实现类 ReentrantLock 可重入锁 ReentrantReadWriteLock.ReadLock ...

    再分享一个Java 多线程断点式下载模块.rar

    多线程断点式下载示例代码,再分享一个Java 多线程断点式下载模块,主要原理是: 把context分为poolSize段,计算每段的长度。如果文件已存在,根据临时文件中记载的线程数量,继续上次的任务,如果下载的目标文件不...

    java 线程安全 是程序执行流的最小单元

    一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点在运行中必不可少的资源,但它可与同属一...

    java专门生产订单id

    java专门生产订单id,不重复,线程安全,经过项目实践

    java自动生成id策略

    1.自动生成id策略. 2.当多线程进入java类,自动生成id.生成规则,根据毫秒然后+3个随机数.

    Java 实例 - 获取线程id源代码+详细指导教程.zip

    Java 实例 - 获取线程id源代码+详细指导教程.zip

    java Swing窗体版多线程下载程序编写示例.rar

    java Swing窗体版多线程下载程序编写示例,多线程下载的实现, 将网络URL中指定的网络文件下载到本地文件中保存。  本代码中将完成新建任务构造器、配置文件构造器,保存下载信息,获取配置文件名,设置在前台显示...

    (附源码)springboot《Java教学》多线程教学演示系统 011733

    主要内容如下五点: 1.Java语言 2.多线程 3.Java多线程 ...此课题研究思路是从基础概念到实现原理,先了解Java语言特点,再了解多线程,从 Java多线程出发进而研究教学演示系统的设计。研究方法如下

    java多线程源码-generator_multiThreadCode:使用Tensorflow在Python中使用词层语言模型的多层递归神经

    java多线程源码基于机器学习的多线程代码生成技术,用于验证Java程序中的并发错误 LSTM-RNN +强化学习 使用Tensorflow在Python中使用词层语言模型的多层递归神经网络(LSTM,RNN)。 灵感来自安德烈·卡帕蒂(Andrej...

    Java socket多线程聊天系统(myeclipse)

    主程序:SFace.java和Face.java 服务器端操作说明: 1、输入本地IP和聊天通信的端口,然后建立服务器; 2、消息接收框里有客户上线与下线的提示; 3、点击“发送信息“或者按”Ctrl+Enter“快捷键向每个在线用户...

    Linux中使用Shell脚本查看Java线程的CPU使用情况

    线上Java应用,在业务高峰期的时候经常出现CPU跑高,需要查看实时的线程占用cpu情况,下面是一个很好用的脚本,可以快速导出每个线程的占用CPU情况,结合jstack日志,排查到具体的线程类名。 一、首先获得jvm的进程...

    一个开源的Java基础工具包

    增加名称、ID,调用次数和时间统计、线程停止接口等,并且在线程运行时,不允许此线程第二次启动。 2、com.baijob.commonTools.thread.Executor 线程池工具类 调用静态方法execute()启动线程,此线程在公共的...

    java解析userAgent中的所有信息

    改资源的注释已经很详细了,但是还是建议配合我的博客一起学习:博客地址:https://blog.csdn.net/qq_23832313/article/details/82775316

    浅谈Android中多线程切换的几种方法

    我们知道,多线程是Android开发中必现的场景,很多...Thread是Java中实现多线程的线程类,每个Thread对象都可以启动一个新的线程,注意是可以启动,也可以不启动新线程: thread.run();//不启动新线程,在当前线程执行

    最新Java面试题视频网盘,Java面试题84集、java面试专属及面试必问课程

    │ │ 9.JAVA并发编程之多线程并发同步业务场景与解决方案.wmv │ │ │ ├─10.微服务架构之Spring Cloud Eureka 场景分析与实战 │ │ 10.微服务架构之Spring Cloud Eureka 场景分析与实战.wmv │ │ │ ├─11....

    java引用虹软sdk,实现完整人脸识别(demo)

    * 注:libarcsoft_face.dll(so)、libarcsoft_face_engine.dll(so)、libarcsoft_face_engine_jni.dll(so)、app-id、sdk-key可以到虹软官网 http://ai.arcsoft.com.cn/ 免费申请下载 * 本地配置:

Global site tag (gtag.js) - Google Analytics