码迷,mamicode.com
首页 > 编程语言 > 详细

守护线程Daemon

时间:2019-12-13 12:09:20      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:tle   exit   isalive   守护   ref   官网   bsp   --   geo   

官网API解释

setDaemon

public final void setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

This method must be invoked before the thread is started.

 

Parameters:
on - if true, marks this thread as a daemon thread
Throws:
IllegalThreadStateException - if this thread is alive
SecurityException - if checkAccess() determines that the current thread cannot modify this thread

setDaemon设置线程为守护线程,必须放到start()方法之前,目的是当前所有运行中的线程为守护线程时该线程结束

使用守护线程模拟心跳实验

package com.dwz.concurrency.chapter4;
/**
 *     使用守护线程模拟心跳实验
 */
public class DaemonThread2 {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            Thread innerThread = new Thread(() -> {
                try {
                    while(true) {
                        System.out.println("Do some thing for health check.");
                        Thread.sleep(1_000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }); 
            
            innerThread.setDaemon(true);
            innerThread.start();
        });
        t.start();
        
        try {
            Thread.sleep(3_000);
            System.out.println("T Thread finish done.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

守护线程Daemon

标签:tle   exit   isalive   守护   ref   官网   bsp   --   geo   

原文地址:https://www.cnblogs.com/zheaven/p/12034273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!