This question already has answers here:
How to start two threads at “exactly” the same time
                                
                                    (4个答案)
                                
                        
                4年前关闭。
            
        

我想启动一个包含许多线程的ThreadGroup,但是start()类中没有ThreadGroup方法。它具有stop()方法来停止线程组。
如果start()方法不可用,如何启动线程组?

请参见下面的代码,因为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());
    }
    }
}

最佳答案

docs


  线程组代表一组线程。


它不是设计为同时.start()多个线程。

您可以将Threads添加到组或其他ThreadGroups,它们可以访问其他Thread的状态,但不能一起启动ThreadGroup。允许Thread访问有关其自身ThreadGroup的信息,但不能访问有关其ThreadGroup的父级ThreadGroup或任何其他ThreadGroups的信息。

有关可用功能的更多信息以及用法示例,请阅读here

关于java - 如何在Java中启动ThreadGroup? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35378936/

10-10 19:01