Tong's Digital Garden

Logo

welcome to Tong's Digital Garden

 bigguaiwutong@qq.com

View My GitHub Profile

守护线程-Daemon Thread

by

守护线程——Daemon Thread

分类

线程的分类:用户线程(User Thread)、守护线程(Daemon Thread)

代码测试

public class TestProject {
    public static void main(String[] args) {
        new WorkerThread().start();
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {
            // handle here exception
        }
        System.out.println("Main Thread ending") ;
    }
}
public class WorkerThread extends Thread{
    public WorkerThread() {
        // 设置是否为守护线程
        // 守护线程只有在初始化时能进行设置,不然就会直接从父类继承,默认为用户线程
        setDaemon(false);
    }

    public void run() {
        int count = 0;

        while (true) {
            System.out.println("Hello from Worker "+count++);

            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // handle exception here
            }
        }
    }
}

可以在设置为用户线程和守护线程时分别执行。

区别

  1. 用户线程不会收到主线程停止的影响并且会阻止 JVM 的推出,守护线程不会阻止由于程序执行完成导致的 JVM 退出

注意

  1. 在使用守护线程中不应该持有任何需要关闭的资源,因为随着 JVM 的退出,守护线程随时可能被中断,可能导致数据的丢失

back

home

tags: 多线程