java并发之守护线程

作者: rejoice001 | 来源:发表于2018-06-28 00:09 被阅读36次

java中有两种线程,用户线程和守护线程
用户线程:主线程停止时,用户线程不会停止
守护线程:主线程停止时,守护线程也会停止
通过setDaemon(true)方法设置为守护线程

package com.rejoice.concurrency;
/**
 * 守护线程:当主线程停止时,子线程自动停止
 * @author jiongyi
 *
 */
public class DaemonThread {
    
    public static void main(String[] args) throws InterruptedException {
        MyThread thread1 = new MyThread();
        thread1.setDaemon(true);//设置子线程为守护线程
        thread1.start();
        Thread.sleep(200);
        System.err.println("主线程停止。。。");
        
    }

    static class  MyThread extends Thread{
        @Override
        public  void  run() {
            while(true) {
                System.err.println("子线程"+Thread.currentThread().getName()+"运行。。。。。");
            }
            
        }
    }
}

运行结果


image.png

相关文章

网友评论

    本文标题:java并发之守护线程

    本文链接:https://www.haomeiwen.com/subject/kdswyftx.html