多线程的守护线程

郎家岭伯爵 2022年05月10日 403次浏览

背景

多线程的守护线程。

实现

Thread的setDaemon方法可设置守护线程。

注:

  • 默认线程均为用户线程,守护线程需要把setDaemon设置为true;
  • 虚拟机必须确保用户线程完成执行,而不用等待守护线程完成执行
  • 守护线程应用场景:后台记录操作、监控内存、垃圾回收等待。

代码

package com.langjialing;

public class ThreadDaemon {
    public static void main(String[] args) {
        UserThread ut = new UserThread();
        DaemonThread dt = new DaemonThread();

        Thread thread = new Thread(dt);
        thread.setDaemon(true); //设置为守护线程
        thread.start();         //启动守护线程

        new Thread(ut).start(); //启动用户线程
    }
}

class UserThread implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 3000; i++) {
            System.out.println("用户线程执行中……" + i);
        }
        System.out.println("用户线程停止执行……");
    }
}

class DaemonThread implements Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("守护线程执行中……");
        }
    }
}

效果

总结

Thread的setDaemon方法可将线程设置为守护线程。

赞助页面示例