Java中使用ThreadGroup来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制。
默认的情况下,所有的线程都属于主线程组。
public final ThreadGroup getThreadGroup()
我们也可以给线程设置分组
Thread(ThreadGroup group,Runnable target,String name)
public class IntegerDemo { public static void main(String[] args) { MyRunnable my = new MyRunnable(); Thread t1 = new Thread(my, "hello"); Thread t2 = new Thread(my, "world"); ThreadGroup tg1 = t1.getThreadGroup(); ThreadGroup tg2 = t2.getThreadGroup(); System.out.println(tg1.getName());// main System.out.println(tg2.getName());// main System.out.println(Thread.currentThread().getThreadGroup().getName());// main } } class MyRunnable implements Runnable { @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }
void setDaemon(boolean daemon);// 更改此线程组的后台程序状态。
public class IntegerDemo { public static void main(String[] args) { method(); } private static void method() { ThreadGroup tg = new ThreadGroup("新的线程组"); MyRunnable my = new MyRunnable(); Thread t1 = new Thread(tg, my, "hello"); Thread t2 = new Thread(tg, my, "world"); tg.setDaemon(true);// 更改此线程组的后台程序状态。 ThreadGroup tg1 = t1.getThreadGroup(); ThreadGroup tg2 = t2.getThreadGroup(); System.out.println(tg1.getName());// 新的线程组 System.out.println(tg2.getName());// 新的线程组 System.out.println(Thread.currentThread().getThreadGroup().getName());// main } } class MyRunnable implements Runnable { @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }