- package com.kxg_04;
- /*
- * 线程组:把多个线程组合到一起
- * 可以对一批线程进行分类管理,java允许程序直接对线程进行控制
- */
- public class ThreadGroupDemo {
- public static void main(String[] args) {
- // 查看线程的默认线程组
- group1();
- // 设置一个线程组,把线程添加进去
- group2();
- }
- private static void group2() {
- // 创建线程组
- ThreadGroup tg = new ThreadGroup("自定义线程组");
- // 创建对象
- MyRunnable mr = new MyRunnable();
- // 创建线程,并把线程添加到线程组中
- 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);
- }
- private static void group1() {
- // 创建对象
- 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);// main
- System.out.println(name2);// main
- // 线程默认情况属于main线程组
- System.out.println(Thread.currentThread().getName());
- }
- }
复制代码- package com.kxg_04;
- public class MyRunnable implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < 100; i++) {
- System.out.println(Thread.currentThread().getName() + ":" + i);
- }
- }
- }
复制代码
|
|