線程組
可以把線程歸屬到某一個線程組中,線程組中可以有線程對象,也可以有線程對象,組中可以有線程,這樣線程組可以類似樹形。
線程組的使用主要是方便線程的管理維護操作:
樣本
(通過線程組的方式組織多個線程並且大量停止所有線程):
1、建立線程A和B
public class ThreadA extends Thread {// 設定新的建構函式,傳入線程組對象public ThreadA(ThreadGroup group, String name) {super(group, name);}public void run() {while (true) {System.out.println("threadA...");// 根據停止標記停止if (this.isInterrupted()) {System.out.println("當前線程:" + this.getName() + "停止了。");break;}}}}public class ThreadB extends Thread {public ThreadB(ThreadGroup group, String name) {super(group, name);// TODO Auto-generated constructor stub}public void run() {while (true) {System.out.println("threadB...");// 根據停止標記停止if (this.isInterrupted()) {System.out.println("當前線程:" + this.getName() + "停止了。");break;}}}}
2、具體測試Client
public class Client {public static void main(String[] args) {try {// 建立線程組ThreadGroup group = new ThreadGroup("自訂線程組");ThreadA threadA = new ThreadA(group, "threadA");ThreadB threadB = new ThreadB(group, "threadB");// 開啟threadA.start();threadB.start();Thread.sleep(1000);// 輸出線程組資訊System.out.println("current thread size :" + group.activeCount());System.out.println("current thread group name :" + group.getName());// 停止線程組內所有線程System.out.println("current thread group stop start...");group.interrupt();System.out.println("current thread group stop end!");} catch (Exception e) {e.printStackTrace();}}}
以上代碼通過線程組組織了多個線程,並且可以使用線程組的interrupt()方法停止所包含的多個線程。
運行之後輸出:
...
threadB...
threadB...
current thread size :2
current thread group name :自訂線程組
current thread group stop start...
threadB...
threadA...
current thread group stop end!
當前線程:threadA停止了。
當前線程:threadB停止了。
備忘:
在執行個體化各個線程的時候,如果不指定所屬的線程組,則這些線程自動歸到當前線程對象所屬的線程組中,也就是說隱似的在一個線程組中添加了子線程。比如:在main方法中建立多個線程,如果不明確的設定所屬線程組的話,則這些線程預設都屬於main所在的線程組。
其中main方法所在的線程組即是main,main線程的父級線程組即是jvm線程組system,可以在main中通過以下擷取:
Thread.currentThread().getThreadGroup().getName();Thread.currentThread().getThreadGroup().getParent().getName()