Java提供了一種在單個對象中組合多個線程的便捷方法。通過這種方式,通過單個方法調用暫停,恢復或中斷線程組。
注意: 現在不推薦使用
suspend()
,resume()
和stop()
方法。
Java線程組由java.lang.ThreadGroup
類實現。
ThreadGroup
表示一組線程。 線程組還可以包括其他線程組。 線程組創建一個樹,其中除初始線程組之外的每個線程組都具有父線程。
允許線程訪問有關其自己的線程組的資訊,但它無法訪問有關其線程組的父線程組或任何其他線程組的資訊。
ThreadGroup類的構造函數
ThreadGroup
類只有兩個構造函數。
編號 | 構造函數 | 描述 |
---|---|---|
1 | ThreadGroup(String name) |
創建具有給定名稱的線程組。 |
2 | ThreadGroup(ThreadGroup parent, String name) |
創建具有給定父組和名稱的線程組。 |
ThreadGroup類的方法
ThreadGroup
類中有許多方法,下麵給出了ThreadGroup
方法的列表。
編號 | 方法 | 描述 |
---|---|---|
1 | void checkAccess() | 此方法確定當前運行的線程是否具有修改線程組的許可權。 |
2 | int activeCount() | 此方法返回線程組及其子組中活動線程數的估計值。 |
3 | int activeGroupCount() | 此方法返回線程組及其子組中活動組數量的估計值。 |
4 | void destroy() | 此方法會銷毀線程組及其所有子組。 |
5 | int enumerate(Thread[] list) | 此方法將線程組及其子組中的每個活動線程複製到指定的數組中。 |
6 | int getMaxPriority() | 此方法返回線程組的最大優先順序。 |
7 | String getName() | 此方法返回線程組的名稱。 |
8 | ThreadGroup getParent() | 此方法返回線程組的父級。 |
9 | void interrupt() | 此方法中斷線程組中的所有線程。 |
10 | boolean isDaemon() | 此方法測試線程組是否為守護程式線程組。 |
11 | void setDaemon(boolean daemon) | 此方法更改線程組的守護程式狀態。 |
12 | boolean isDestroyed() | 此方法測試此線程組是否已被銷毀。 |
13 | void list() | 此方法將有關線程組的資訊列印到標準輸出。 |
14 | boolean parentOf(ThreadGroup g) | 此方法測試線程組是線程組參數還是其祖先線程組之一。 |
15 | void suspend() | 此方法用於掛起線程組中的所有線程。 |
16 | void resume() | 此方法用於恢復使用suspend() 方法掛起的線程組中的所有線程。 |
17 | void setMaxPriority(int pri) | 此方法設置組的最大優先順序。 |
18 | void stop() | 此方法用於停止線程組中的所有線程。 |
19 | String toString() | 此方法返回線程組的字串表示形式。 |
下麵來一個分組多個線程的代碼。
ThreadGroup tg1 = new ThreadGroup("Group A");
Thread t1 = new Thread(tg1,new MyRunnable(),"one");
Thread t2 = new Thread(tg1,new MyRunnable(),"two");
Thread t3 = new Thread(tg1,new MyRunnable(),"three");
現在所有3
個線程都屬於一個組。 這裏,tg1
是線程組名稱,MyRunnable
是實現Runnable
介面的類,“one”,“two”和“three”是線程名稱。
現在只能通過一行代碼中斷所有線程。
Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup示例
示例: ThreadGroupDemo.java
package com.zaixian;
public class ThreadGroupDemo implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable, "one");
t1.start();
Thread t2 = new Thread(tg1, runnable, "two");
t2.start();
Thread t3 = new Thread(tg1, runnable, "three");
t3.start();
System.out.println("Thread Group Name: " + tg1.getName());
tg1.list();
}
}
執行上面示例代碼,得到以下結果:
Thread Group Name: Parent ThreadGroup
three
two
one
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
上一篇:
Java線程池
下一篇:
Java關閉掛鉤(shutdown hook)