/**
*
*/
public class Daemons {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread d = new Thread(new Daemon());
d.setDaemon(true); //
d.start();
System.out.println("d.isDaemon() = " + d.isDaemon() + ".");
TimeUnit.SECONDS.sleep(1);
}
}
class DaemonSpawn implements Runnable {
public void run() {
while (true) {
Thread.yield();
}
}
}
class Daemon implements Runnable {
private Thread[] t = new Thread[10];
public void run() {
for (int i=0; i<t.length; iPP) {
t[i] = new Thread(new DaemonSpawn());
t[i].start();
System.out.println("DaemonSpawn " + i + " started.");
}
for (int i=0; i<t.length; iPP) {
System.out.println("t[" + i + "].isDaemon() = " +
t[i].isDaemon() + ".");
}
while (true) {
Thread.yield();
}
}
}
run result:
d.isDaemon () = true.
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. < true. > t [2] .isDaemon () = br
t () = true.
t [7] .isDaemon () = true.
t [8] .isDaemon () = true.
t [9] .isDaemon () = true.
on page 664 of the second edition, I see that these two while () yield () (keep the task in the state of giving up thread);
keep letting out thread? What"s the point? For example, DaemonSpawn, why don"t you just let him finish the task quietly? After executing
, the thread is freed. What"s the point of while () yield (); in Daemon? Main already starts only one thread to execute Daemon tasks
. Wouldn"t it be nice to let him do it calmly? Diagonal ignorance, linear ignorance
can anyone explain it systematically?
ps: has been learning about threading recently. Do you have any methods, books or approaches? It"s hard to see think in java.