Daemon线程——在所有的非Daemon线程结束后JVM会停止。利用Daemon线程的特性,不停输出目前运行的线程,然后判断主线程与子线程的关系。
似乎主线程结束后,子线程还在继续的样子,但我并不能确定。
附上代码
1 public class ThreadDemo { 2 public static void main(String[] args) { 3 System.out.println("start-当前活动的线程数" + Thread.activeCount()); 4 { 5 ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); 6 int noThreads = currentGroup.activeCount(); 7 Thread[] lstThreads = new Thread[noThreads]; 8 currentGroup.enumerate(lstThreads); 9 for (int i = 0; i < noThreads; i++) 10 System.out.println("线程号:" + i + " = " + lstThreads[i].getName()); 11 System.out.println(); 12 } 13 14 Thread thread = new Thread("thread") { 15 @Override 16 public void run() { 17 System.out.println("thread over"); 18 } 19 }; 20 21 Thread daemon = new Thread("daemon") { 22 @Override 23 public synchronized void run() { 24 while (true) { 25 // thread.isAlive(); 26 // System.out.println("当前活动的线程数"+Thread.activeCount()); 27 { 28 ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); 29 int noThreads = currentGroup.activeCount(); 30 Thread[] lstThreads = new Thread[noThreads]; 31 currentGroup.enumerate(lstThreads); 32 for (int i = 0; i < noThreads; i++) 33 System.out.println("线程号:" + i + " = " + lstThreads[i].getName()); 34 System.out.println(); 35 } 36 } 37 } 38 }; 39 daemon.setDaemon(true); 40 41 daemon.start(); 42 thread.start(); 43 44 System.out.println("end-当前活动的线程数" + Thread.activeCount()); 45 { 46 ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); 47 int noThreads = currentGroup.activeCount(); 48 Thread[] lstThreads = new Thread[noThreads]; 49 currentGroup.enumerate(lstThreads); 50 for (int i = 0; i < noThreads; i++) 51 System.out.println("线程号:" + i + " = " + lstThreads[i].getName()); 52 System.out.println(); 53 } 54 } 55 }