【线程控制:线程守护】

线程守护:当正在运行的线程都是守护线程时,Java 虚拟机退出。 该方法必须在启动线程前调用。

package com.shusheng.tihuzhai.test;

/**
 * @author shusheng
 * @description
 * @Email shusheng@yiji.com
 * @date 2018/8/28 10:40
 */
public class ThreadDaemon extends Thread{

    @Override
    public void run() {
        for (int x = 0; x < 100; x++) {
            System.out.println(getName() + ":" + x);
        }
    }

}
package com.shusheng.tihuzhai.test;

/**
 * @author shusheng
 * @description
 * @Email shusheng@yiji.com
 * @date 2018/8/28 14:49
 */
public class ThreadDaemonTest {

    public static void main(String[] args) {

        ThreadDaemon td1 = new ThreadDaemon();
        ThreadDaemon td2 = new ThreadDaemon();
        td1.setName("叶胖子");
        td2.setName("王瘦子");
        // 设置守护线程
        td1.setDaemon(true);
        td2.setDaemon(true);
        td1.start();
        td2.start();

        Thread.currentThread().setName("陈苗条");
        for (int x = 0; x < 3; x++) {
            System.out.println(Thread.currentThread().getName() + ":" + x);
        }

    }

}

运行结果之一:

陈苗条:0
陈苗条:1
陈苗条:2
王瘦子:0
王瘦子:1
王瘦子:2
王瘦子:3
终身学习者
原文地址:https://www.cnblogs.com/zuixinxian/p/9548301.html