如何在 java 中启动 ThreadGroup?
How to start ThreadGroup in java?
我想启动一个包含许多线程的 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());
}
}
}
我想启动一个包含许多线程的 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());
}
}
}