0

我想启动一个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());
    }
    }
}
4

1 回答 1

2

文档

一个线程组代表一组线程。

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

可以添加Threads到 group 或者 otherThreadGroups中,可以访问 otherThread的状态,但不能ThreadGroup一起启动 a。AThread被允许访问关于它自己的信息ThreadGroup,但不能访问关于它ThreadGroup的父母ThreadGroup或任何其他人的信息ThreadGroups

有关使用示例的可用功能的更多信息,请阅读此处

于 2016-02-13T11:00:50.293 回答