标签:情况 proc imp void RoCE rtu public 一个 while
1、设置线程为后台线程
注意,main线程为非后台线程,main线程结束,则不管后台线程是否结束,都会杀死非后台线程
1 /** 2 * 后台线程 3 */ 4 public class SimpleDaemons implements Runnable { 5 public void run() { 6 try { 7 while (true) { 8 TimeUnit.MILLISECONDS.sleep(100); 9 print(Thread.currentThread() + " " + this); 10 } 11 } catch (InterruptedException e) { 12 print("sleep() interrupted"); 13 } 14 } 15 public static void main(String[] args) throws Exception { 16 for (int i = 0; i < 10; i++) { 17 Thread daemon = new Thread(new SimpleDaemons()); 18 //设置为后台线程 19 daemon.setDaemon(true); // Must call before start() 20 daemon.start(); 21 } 22 print("All daemons started"); 23 TimeUnit.MILLISECONDS.sleep(1750); 24 } 25 }
2、后台线程特性
a.如果一个线程时后台线程,那么由它创建的任何线程都将自动被设置为后台线程
1 /** 2 * 如果一个线程时后台线程,那么由它创建的任何线程都将自动被设置为后台线程 3 */ 4 class Daemon implements Runnable { 5 private Thread[] t = new Thread[10]; 6 public void run() { 7 for (int i = 0; i < t.length; i++) { 8 //派生出的子线程t[i]都默认为后台线程 9 t[i] = new Thread(new DaemonSpawn()); 10 t[i].start(); 11 printnb("DaemonSpawn " + i + " started, "); 12 } 13 for (int i = 0; i < t.length; i++) 14 printnb("t[" + i + "].isDaemon() = " + t[i].isDaemon() + ", "); 15 while (true) 16 Thread.yield(); 17 } 18 } 19 20 class DaemonSpawn implements Runnable { 21 public void run() { 22 while (true) 23 Thread.yield(); 24 } 25 } 26 27 public class Daemons { 28 public static void main(String[] args) throws Exception { 29 Thread d = new Thread(new Daemon()); 30 // 线程d被设置为后台线程,则其派生出的子线程(由new Daemon()创建)默认的也为后台线程 31 d.setDaemon(true); 32 d.start(); 33 printnb("d.isDaemon() = " + d.isDaemon() + ", "); 34 // Allow the daemon threads to 35 // finish their startup processes: 36 TimeUnit.SECONDS.sleep(1); 37 } 38 }
b.后台线程在不执行finally子句的情况下就会终止其run()方法
换句话说,finally子句不是一定执行的,如果是在后台线程中,finally子句可能不会执行就结束了
1 /** 2 * 后台线程中的finally子句可能不会执行,决定于非后台线程什么时候结束 3 */ 4 class ADaemon implements Runnable { 5 public void run() { 6 try { 7 print("Starting ADaemon"); 8 TimeUnit.SECONDS.sleep(1); 9 } catch (InterruptedException e) { 10 print("Exiting via InterruptedException"); 11 } finally { 12 print("This should always run?"); 13 } 14 } 15 } 16 17 public class DaemonsDontRunFinally { 18 public static void main(String[] args) throws Exception { 19 Thread t = new Thread(new ADaemon()); 20 t.setDaemon(true); 21 t.start(); 22 //如果不加延时,可能都不会执行print("Starting ADaemon"); 23 TimeUnit.SECONDS.sleep(1); 24 } 25 }
标签:情况 proc imp void RoCE rtu public 一个 while
原文地址:https://www.cnblogs.com/6xiong/p/12005597.html