2016-02-13 29 views
0

我想開始一個ThreadGroup其中包含很多線程,但start()方法不存在於ThreadGroup類。它有一個stop()方法來停止線程組。 如果start()方法不可用,如何啓動線程組?如何在java中啓動ThreadGroup?

請看下面的代碼,我可以一個一個啓動線程但不能啓動線程組,因爲start()方法不存在於ThreadGroup類中。要求是我們需要同時啓動線程組,這個怎麼做?

public class ThreadGroupExample 
{ 
    public static void main(String[] args) 
    { 
    ThreadGroup thGroup1 = new ThreadGroup("ThreadGroup1"); 

    /* createting threads and adding into thread grout "thGroup1" */ 
    Thread1 th1 = new Thread1(thGroup1, "JAVA"); 
    Thread1 th2 = new Thread1(thGroup1, "JDBC"); 
    Thread2 th3 = new Thread2(thGroup1, "EJB"); 
    Thread2 th4 = new Thread2(thGroup1, "XML"); 

    /* starting all thread one by one */ 
    th1.start(); 
    th2.start(); 
    th3.start(); 
    th4.start(); 

    // thGroup1.start(); 

    thGroup1.stop(); 

    } 
} 

class Thread1 extends Thread 
{ 
    Thread1(ThreadGroup tg, String name) 
    { 
    super(tg, name); 
    } 

    @Override 
    public void run() 
    { 
    for (int i = 0; i < 10; i++) 
    { 
     ThreadGroup tg = getThreadGroup(); 
     System.out.println(getName() + "\t" + i + "\t" + getPriority() 
      + "\t" + tg.getName()); 
    } 
    } 
} 

class Thread2 extends Thread 
{ 

    Thread2(String name) 
    { 
    super(name); 
    } 

    Thread2(ThreadGroup tg, String name) 
    { 
    super(tg, name); 
    } 

    @Override 
    public void run() 
    { 
    for (int i = 0; i < 10; i++) 
    { 
     ThreadGroup tg = getThreadGroup(); 
     System.out.println(getName() + "\t" + i + "\t" + getPriority() 
      + "\t" + tg.getName()); 
    } 
    } 
} 
+0

ThreadGroup無法啓動其所有線程,原因很簡單,只有在線程啓動時纔將線程實際添加到組中。請注意,'ThreadGroup'中的**不推薦和危險的**'stop()'和'suspend()'方法只是運行你試圖避免的同一種順序循環。 – RealSkeptic

+0

@RealSkeptic你確定它是重複的嗎?我規定了這個事實,這個事件是OP的事情,但是這個問題是關於一個不同的話題/問題,在這個事件中沒有解釋。請重新考慮這一點。 – Idos

+1

@Idos我認爲它的當前形式是一個XY問題,其中實際問題是重複的,ThreadGroup問題僅次於它。您的回答和我的評論提供了足夠的信息來解釋爲什麼ThreadGroup與解決此問題無關,但對OP的任何實際答案實際上都是對該欺騙的答案。 – RealSkeptic

回答

2

docs

線程組代表一組螺紋。

它不同時設計.start()多個線程。

您可以將Threads添加到該組或其他ThreadGroups,該組可以訪問其他Thread的狀態,但不能同時啓動ThreadGroup。允許Thread訪問有關其自己的ThreadGroup的信息,但不訪問有關其ThreadGroup的父母ThreadGroup或任何其他ThreadGroups的信息。

有關使用示例的可用功能的更多信息,請參閱here