本文詳細介紹了Java中的線程組(ThreadGroup)的概念以及代碼示範!
文章目錄
- 1 概念
- 2 構造器和常用方法
- 3 使用
1 概念
public class ThreadGroup
extends Object
implements Thread.UncaughtExceptionHandler
線程組:多個線程存放在一個組中,友善對線程的統一管理。Java中具有專門的線程組對象,對應ThreadGroup類。如果建立的線程沒有指定任何的組,那麼這個線程在main組當中。
2 構造器和常用方法
構造器:
/**
* 建立一個新線程組。新線程組的父線程組是目前正在運作線程的線程組。
*
* @param name 新線程組的名稱
*/
public ThreadGroup(String name)
/**
* 建立一個新線程組。新線程組的父線程組是指定的線程組。
*
* @param parent 父線程組
* @param name 新線程組的名稱。
*/
public ThreadGroup(ThreadGroup parent, String name)
常用方法:
// 擷取目前線程所線上程組的活動線程總數(估計)。
threadGroup.activeCount() //或者下面的方法
Thread.activeCount()
//擷取該線程組的父線程組
threadGroup.getParent()
//擷取目前線程所屬線程組
Thread.currentThread().getThreadGroup()
3 使用
常常結合Thread的構造器進行使用,用來對一批線程進行分組,友善追蹤。
//擷取main線程的線程組
System.out.println(Thread.currentThread().getThreadGroup());
//擷取目前線程的線程組中的活動線程數
System.out.println(Thread.activeCount());
//擷取main線程的線程組資訊
System.out.println(Thread.currentThread());
//建立線程組
ThreadGroup threadGroup = new ThreadGroup("新線程組");
//擷取該線程組的父線程組,可以看到,它的父線程組是main線程組
ThreadGroup parent = threadGroup.getParent();
System.out.println(parent);
//建立子線程,加入該線程組
Thread thread = new Thread(threadGroup, "子線程");
//列印該子線程資訊
System.out.println(thread);
列印的線程對象的格式:
Thread[子線程,5,新線程組]
Thread[main,5,main]
其中:
Thread-0——線程的名稱
5——線程預設的優先級
main——線程所在的組:main(如果建立的線程沒有指定任何的組,那麼這個線程預設在main線程組當中)。
如果有什麼不懂或者需要交流,可以留言。另外希望點贊、收藏、關注,我将不間斷更新各種Java學習部落格!