---
title: "Daemon threads"
author: "BBjava"
date: "2011-09-26T11:41:41Z"
tags: []
categories: ["编程语言"]
slug: "daemon-threads"
draft: false
lastmod: "2011-10-03T15:15:43Z"
id: 1180490
url: "https://bbjava.iteye.com/blog/1180490"
---

"Daemon thread"是为提供普通服务在后台运行，跟寄主程序同样生命的，却不属于寄主程序的一个线程。寄主程序（non-daemon thread）一但终止，整个程序也就结束了，即使"Daemon thread"还没有运行到结尾.也就是说non-daemon thread终止，daemon thread也终止。
下面例子是引用自tij4的: 

> [code=java]package org.iteye.bbjava.concurrency.daemon;
> 
> import java.util.concurrent.TimeUnit;
> 
> public class SimpleDaemons implements Runnable {
> 
> 	@Override
> 	public void run() {
> 		try {
> 			while (true) {
> 				TimeUnit.MICROSECONDS.sleep(100);
> 				System.out.println(Thread.currentThread() + " " + this);
> 			}
> 		} catch (InterruptedException e) {
> 			System.out.println("sleep interrupted!");
> 		}
> 	}
> 
> 	public static void main(String[] args) throws InterruptedException {
> 		for (int i = 0; i < 10; i++) {
> 			Thread daemon = new Thread(new SimpleDaemons());
> 			daemon.setDaemon(true);
> 			daemon.start();
> 		}
> 		System.out.println("All daemon started!");
> 		TimeUnit.MILLISECONDS.sleep(175);
> 	}
> 
> }
> [/code]