代码整体不难,只是想了解下自己对下面这段代码各个问题的理解是否正确。
import java.util.concurrent.*;
import static net.mindview.util.Print.*;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()); //1、将一个继承了 Runnable 的对象传到 new Thread() 中是指将一个任务传到一个线程中?
t[i].start();
printnb("DaemonSpawn " + i + " started, ");
}
for(int i = 0; i < t.length; i++)
printnb("t[" + i + "].isDaemon() = " + t[i].isDaemon() + ", ");
while(true)
Thread.yield(); //2、我觉得这里调不调用似乎没啥区别,而且干嘛要使用 while 循环?
}
}class DaemonSpawn implements Runnable {
public void run() {
while(true)
Thread.yield(); //3、同上
}
}public class Daemons {
public static void main(String[] args) throws Exception {
Thread d = new Thread(new Daemon());
d.setDaemon(true);
d.start();
printnb("d.isDaemon() = " + d.isDaemon() + ", ");
TimeUnit.SECONDS.sleep(1); //4、你说这程序干嘛要设计让它 sleep() 1秒?
}
}
import java.util.concurrent.*;
import static net.mindview.util.Print.*;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()); //1、将一个继承了 Runnable 的对象传到 new Thread() 中是指将一个任务传到一个线程中?
t[i].start();
printnb("DaemonSpawn " + i + " started, ");
}
for(int i = 0; i < t.length; i++)
printnb("t[" + i + "].isDaemon() = " + t[i].isDaemon() + ", ");
while(true)
Thread.yield(); //2、我觉得这里调不调用似乎没啥区别,而且干嘛要使用 while 循环?
}
}class DaemonSpawn implements Runnable {
public void run() {
while(true)
Thread.yield(); //3、同上
}
}public class Daemons {
public static void main(String[] args) throws Exception {
Thread d = new Thread(new Daemon());
d.setDaemon(true);
d.start();
printnb("d.isDaemon() = " + d.isDaemon() + ", ");
TimeUnit.SECONDS.sleep(1); //4、你说这程序干嘛要设计让它 sleep() 1秒?
}
}
1.在线程中启动线程。
2.Bruce大师说过,一般线程总是以某种方式来循环,所以写的代码也尽量秉承这个原则。
3.
4.这个程序应该是示例的后台线程创建出来的线程亦是后台线程,既然为后台线程,那么main()线程一结束,那么后台就跟着结束了,当然也就什么也不会发生了,所以sleep(1),给后台个执行的机会。
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,
不过加了while就是上一层的线程不断的干扰下一层的进程的运行时间。不知道此线程本身会不会被自己停?