//: Daemons.java ////////////////////////////////////////////////// // Copyright (c) Bruce Eckel, 1998 // Daemonic behavior import java.io.*; class Daemon extends Thread { private static final int SIZE = 1000; 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 Daemons { 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) {} } }
% java Daemons 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