以上结果说明了守护线程中产生的新线程也是守护线程。
如果将mian函数中的TimeUnit.SECONDS.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.
|
以上结果说明了如果用户线程已经全部退出运行了,只剩下守护线程存在了,虚拟机也就退出了。下面的例子也说明了这个问题。
代码示例:
- import java.util.concurrent.TimeUnit;
- /**
- * Finally shoud be always run ?
- */
- public class DaemonsDontRunFinally {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Thread t = new Thread(new ADaemon());
- t.setDaemon(true);
- t.start();
- }
- }
- class ADaemon implements Runnable {
- public void run() {
- try {
- System.out.println("start ADaemon...");
- TimeUnit.SECONDS.sleep(1);
- } catch (InterruptedException e) {
- System.out.println("Exiting via InterruptedException");
- } finally {
- System.out.println("This shoud be always run ?");
- }
- }
- }
|
运行结果:
start ADaemon...
如果将main函数中的t.setDaemon(true);注释掉,运行结果如下:
start ADaemon...
This shoud be always run ?