A:线程组概述
* Java中使用ThreadGroup来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制。* 默认情况下,所有的线程都属于主线程组。 * public final ThreadGroup getThreadGroup()//通过线程对象获取他所属于的组 * public final String getName()//通过线程组对象获取他组的名字* 我们也可以给线程设置分组 * 1,ThreadGroup(String name) 创建线程组对象并给其赋值名字 * 2,创建线程对象 * 3,Thread(ThreadGroup?group, Runnable?target, String?name) * 4,设置整组的优先级或者守护线程
B:案例演示
* 线程组的使用,默认是主线程组
MyRunnable mr = new MyRunnable();Thread t1 = new Thread(mr, "张三");Thread t2 = new Thread(mr, "李四");//获取线程组// 线程类里面的方法:public final ThreadGroup getThreadGroup()ThreadGroup tg1 = t1.getThreadGroup();ThreadGroup tg2 = t2.getThreadGroup();// 线程组里面的方法:public final String getName()String name1 = tg1.getName();String name2 = tg2.getName();System.out.println(name1);System.out.println(name2);// 通过结果我们知道了:线程默认情况下属于main线程组// 通过下面的测试,你应该能够看到,默任情况下,所有的线程都属于同一个组System.out.println(Thread.currentThread().getThreadGroup().getName());
自己设定线程组
// ThreadGroup(String name)ThreadGroup tg = new ThreadGroup("这是一个新的组");MyRunnable mr = new MyRunnable();// Thread(ThreadGroup group, Runnable target, String name)Thread t1 = new Thread(tg, mr, "张三");Thread t2 = new Thread(tg, mr, "李四");System.out.println(t1.getThreadGroup().getName());System.out.println(t2.getThreadGroup().getName());//通过组名称设置后台线程,表示该组的线程都是后台线程tg.setDaemon(true);``
/** * @param args * ThreadGroup */public static void main(String[] args) { //demo1(); ThreadGroup tg = new ThreadGroup("我是一个新的线程组"); //创建新的线程组 MyRunnable mr = new MyRunnable(); //创建Runnable的子类对象 Thread t1 = new Thread(tg, mr, "张三"); //将线程t1放在组中 Thread t2 = new Thread(tg, mr, "李四"); //将线程t2放在组中 System.out.println(t1.getThreadGroup().getName()); //获取组名 System.out.println(t2.getThreadGroup().getName()); tg.setDaemon(true);}public static void demo1() { MyRunnable mr = new MyRunnable(); Thread t1 = new Thread(mr, "张三"); Thread t2 = new Thread(mr, "李四"); ThreadGroup tg1 = t1.getThreadGroup(); ThreadGroup tg2 = t2.getThreadGroup(); System.out.println(tg1.getName()); //默认的是主线程 System.out.println(tg2.getName());}
}
class MyRunnable implements Runnable {
@Overridepublic void run() { for(int i = 0; i < 1000; i++) { System.out.println(Thread.currentThread().getName() + "...." + i); }}