【发布时间】:2016-02-13 10:49:11
【问题描述】:
我想启动一个包含许多线程的ThreadGroup,但ThreadGroup 类中不存在start() 方法。它有一个stop() 方法来停止线程组。
如果start()方法不可用,如何启动线程组?
请看下面的代码,我可以一个一个地启动线程但不能启动线程组,因为ThreadGroup类中没有start()方法。需求是我们需要同时启动线程组,怎么做?
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());
}
}
}
【问题讨论】:
-
A
ThreadGroup将无法启动其所有线程,原因很简单,线程实际上仅在启动时才添加到组中。请注意,ThreadGroup中的已弃用和危险stop()和suspend()方法只是运行您试图避免的相同类型的顺序循环。 -
@RealSkeptic 你确定它是重复的吗?我规定 dup 是 OP 所追求的,但问题是关于 dup 中未解释的不同主题/问题。请重新考虑。
-
@Idos 我相信它目前的形式是一个 XY 问题,其中实际问题是重复的,
ThreadGroup问题只是次要问题。您的回答和我的评论提供了足够的信息来解释为什么 ThreadGroup 与解决此问题无关,但是对 OP 的任何真正回答实际上都是对欺骗的回答。
标签: java multithreading synchronization threadgroup