守护线程

守护线程

守护线程包括后台记录、垃圾回收等杂事。java虚拟机只会保证用户线程执行完毕,而守护线程不被保证。

以下代码自定义一个守护线程:

package com.cxf.multithread.daemon;

public class TestForDaemon {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyJob());
        Thread thread2 = new Thread(new Daemon());
        thread2.setDaemon(true);
        thread1.start();
        thread2.start();
    }
}

class MyJob implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("i am running");
        }
        System.out.println("job finished");
    }
}

class Daemon implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Daemon is running");
        }
        System.out.println("Daemon finished");
    }
}

输出结果:

i am running
i am running
i am running
i am running
i am running
job finished
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running
Daemon is running

使用setDaemon方法来让一个线程变为守护线程。

上一篇:20191317王鹏宇第四章学习笔记


下一篇:k8s中pod的几个阶段