Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2066344
  • 博文数量: 519
  • 博客积分: 10070
  • 博客等级: 上将
  • 技术积分: 3985
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-29 14:05
个人简介

只问耕耘

文章分类

全部博文(519)

文章存档

2016年(1)

2013年(5)

2011年(46)

2010年(220)

2009年(51)

2008年(39)

2007年(141)

2006年(16)

我的朋友

分类: Java

2010-01-18 15:31:30

“Daemon”线程的作用是在程序的运行期间于后台提供一种“常规”服务,但它并不属于程序的一个基本部分。因此,一旦所有非Daemon线程完成,程序也会中止运行。相反,假若有任何非Daemon线程仍在运行(比如还有一个正在运行main()的线程),则程序的运行不会中止。
通过调用isDaemon(),可调查一个线程是不是一个Daemon,而且能用setDaemon()打开或者关闭一个线程的Daemon状态。如果是一个Daemon线程,那么它创建的任何线程也会自动具备Daemon属性。
下面这个例子演示了Daemon线程的用法:
 
package c1;
import java.io.*;
class Daemon extends Thread {
   private static final int SIZE = 10;
   private Thread[] t = new Thread[SIZE];
   public Daemon() {
     setDaemon(true);   
     start();    
   }
   public void run() {
     for(int i = 0; i < SIZE; i++)
       t[i] = new DaemonSpawn(i);
     for(int i = 0; i < SIZE; i++)
       System.out.println(
         "t[" + i + "].isDaemon() = "
         + t[i].isDaemon());
     while(true)
       yield();
   }
 }
 class DaemonSpawn extends Thread {
   public DaemonSpawn(int i) {
     System.out.println(
       "DaemonSpawn " + i + " started");
     start();
   }
   public void run() {
     while(true)
       yield();
   }
 }
 public class Test {
   public static void main(String[] args) {
     Thread d = new Daemon();
     System.out.println(
       "d.isDaemon() = " + d.isDaemon());
     // Allow the daemon threads to finish
     // their startup processes:
     BufferedReader stdin =
       new BufferedReader(
         new InputStreamReader(System.in));
     System.out.println("Waiting for CR");
     try {
       stdin.readLine();
     } catch(IOException e) {}
   }
 }
/*
输出结果:
d.isDaemon() = true
Waiting for CR
DaemonSpawn 0 started
DaemonSpawn 1 started
DaemonSpawn 2 started
DaemonSpawn 3 started
DaemonSpawn 4 started
DaemonSpawn 5 started
DaemonSpawn 6 started
DaemonSpawn 7 started
DaemonSpawn 8 started
DaemonSpawn 9 started
t[0].isDaemon() = true
t[1].isDaemon() = true
t[2].isDaemon() = true
t[3].isDaemon() = true
t[4].isDaemon() = true
t[5].isDaemon() = true
t[6].isDaemon() = true
t[7].isDaemon() = true
t[8].isDaemon() = true
t[9].isDaemon() = true

 */ 
阅读(1991) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~