線程組使用

來源:互聯網
上載者:User

線程組

可以把線程歸屬到某一個線程組中,線程組中可以有線程對象,也可以有線程對象,組中可以有線程,這樣線程組可以類似樹形。

線程組的使用主要是方便線程的管理維護操作:



樣本

(通過線程組的方式組織多個線程並且大量停止所有線程):

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()







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.