Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

7.9. 守护线程

		
package cn.netkiller.test;

public class Test {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread());

        Thread t = new Thread(() -> {
            Thread.currentThread().setName("netkiller");
            System.out.println(Thread.currentThread().getName() + ": running...");
            while (true) {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread() + " - " + System.currentTimeMillis());
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                    break;
                }
            }
        });
        t.setDaemon(true);//设置为守护线程【表示守护主线程,随主线程结束而结束】
        t.start();

        while (t.isAlive()) {
            try {
                
                ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
                int activeCount = currentGroup.activeCount();
                Thread[] threads = new Thread[activeCount];
                currentGroup.enumerate(threads);
                for (Thread thread : threads) {
                    System.out.println("线程号:" + thread.getId() + " = " + thread.getName() + " 线程状态:" + thread.getState());
                }
                Thread.sleep(5000);
                t.interrupt();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}