Java编程思想 第四版 c21 并发 学习笔记
练习7:在Daemons.java中使用不同的休眠时间,并观察结果。
package jiangning.c21.ex;
import java.util.concurrent.TimeUnit;
/**
* Java编程思想 第四版 c21 并发 练习7:在Daemons.java中,使用不同的休眠时间,观察不同结果
*
* @author JiangNing
*
*/
class Daemon implements Runnable {
private Thread[] t = new Thread[10];
public void run() {
for (int i = 0; i < t.length; i++) {
t[i] = new Thread(new DaemonSpawn());
t[i].start();
System. out.println("DaemonSpawn " + i + " started"); // 打印出执行了那个线程
}
for (int i = 0; i < t.length; i++) {
System. out.println("t[" + i + "].isDaemon " + t[i].isDaemon());// 打印线程是否为后台线程
}
while (true ) {
Thread. yield();
}
}
}
class DaemonSpawn implements Runnable {
public void run() {
while (true ) {
Thread. yield();
}
}
}
public class Exercise7 {
public static void main(String[] args) throws Exception {
Thread d = new Thread(new Daemon());
d.setDaemon( true);
d.start();
System. out.println("d.isDaemon()= " + d.isDaemon() + ",");
TimeUnit. MILLISECONDS.sleep(5000);
}
}
/**
* 输入不同的时间,结果都是一样的。
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
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
*/