java多线程总结二:后台线程(守护线程)
所谓的后台线程,是指在程序运行的时候在后台提供一种通用服务的线程,并且这种线程并不属于程序中不可或缺的部分。因此当所有的非后台线程结束时,程序也就终止了,同时会杀死所有后台线程。反过来说,只要有任何非后台线程(用户线程)还在运行,程序就不会终止。后台线程在不执行finally子句的情况下就会终止其run方法。后台线程创建的子线程也是后台线程。
下面是一个后台线程的示例:
1 package com.muzeet.testThread; 2 3 import java.util.concurrent.TimeUnit; 4 5 public class DeamonDemo implements Runnable { 6 @Override 7 public void run() { 8 try { 9 while (true) { 10 Thread.sleep(1000); 11 System.out.println("#" + Thread.currentThread().getName()); 12 13 14 } 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } finally { 18 // 后台线程不执行finally子句 19 System.out.println("finally "); 20 } 21 } 22 23 public static void main(String[] args) { 24 for (int i = 0; i < 10; i++) { 25 Thread daemon = new Thread(new DeamonDemo()); 26 // 必须在start之前设置为后台线程 27 daemon.setDaemon(true); 28 daemon.start(); 29 30 } 31 System.out.println("All deamons started"); 32 try { 33 TimeUnit.MILLISECONDS.sleep(10000); 34 } catch (InterruptedException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 } 38 } 39 }
运行结果:
All deamons started #Thread-2 #Thread-0 #Thread-6 #Thread-4 #Thread-8 #Thread-9 #Thread-5 #Thread-7 #Thread-3 #Thread-1 #Thread-2 #Thread-4 #Thread-6 #Thread-0 #Thread-8 #Thread-9 #Thread-7 #Thread-5 #Thread-3 #Thread-1 #Thread-4 #Thread-6 #Thread-0 #Thread-2 #Thread-8 #Thread-9 #Thread-7 #Thread-5 #Thread-3 #Thread-1 #Thread-6 #Thread-4 #Thread-2 #Thread-0 #Thread-8 #Thread-9 #Thread-5 #Thread-7 #Thread-3 #Thread-1 #Thread-4 #Thread-0 #Thread-2 #Thread-6 #Thread-8 #Thread-9 #Thread-5 #Thread-7 #Thread-3 #Thread-1 #Thread-0 #Thread-2 #Thread-6 #Thread-4 #Thread-8 #Thread-1 #Thread-3 #Thread-7 #Thread-5 #Thread-9 #Thread-0 #Thread-6 #Thread-2 #Thread-4 #Thread-8 #Thread-9 #Thread-7 #Thread-5 #Thread-1 #Thread-3
分析:从结果可以看出,十个子线程并没有无线循环的打印(而是在主线程sleep的10s中,所有子线程各输出10次,每个子线程sleep1s),而是在主线程(main())退出后,JVM强制关闭所有后台线程。而不会有任何希望出现的确认形式,如finally子句不执行。