java - java中如何启动ThreadGroup?

标签 java multithreading synchronization threadgroup

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

请看下面的代码,我可以一一启动线程但无法启动线程组,因为start() ThreadGroup 中不存在该方法类(class)。需求是我们需要同时启动线程组,怎么办?

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 :

A thread group represents a set of threads.

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

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

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

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

相关文章:

MySql phpMyAdmin : Replicating/Synchronizng two Database automatically

amazon-web-services - 如何将 AWS S3 存储桶与目录同步并且不保留旧版本

java - for循环中的同步方法

java - 使用 freets 在 java 中进行语音识别

java - 如何根据当前日期(包括java中的当前日期)获取最近三个月的第一个日期和最后一个日期?

java - 如果多个线程访问同一个私有(private)方法,变量值会混合吗?

c# - 管理 .NET WinForm 应用程序中的线程

java - 将监听器添加到下拉菜单

java/xuggle - 将图像数组编码到电影中

java - 如何在通过JUnit测试的多线程应用程序中调试断点?