zoukankan      html  css  js  c++  java
  • JAVA后台线程(守护线程)

    所谓的后台线程,是指在程序运行的时候在后台提供一种通用服务的线程,并且这种线程并不属于程序中不可或缺的部分。因此当所有的非后台线程结束时,程序也就终止了,同时会杀死所有后台线程。反过来说,只要有任何非后台线程(用户线程)还在运行,程序就不会终止。后台线程在不执行finally子句的情况下就会终止其run方法后台线程创建的子线程也是后台线程。

    下面是一个后台线程的示例:

    1. <span style="font-size:16px;">package demo.thread;  
    2.   
    3. import java.util.concurrent.TimeUnit;  
    4.   
    5. public class DaemonDemo 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.         } catch (InterruptedException e) {  
    14.             e.printStackTrace();  
    15.         } finally {// 后台线程不执行finally子句  
    16.             System.out.println("finally ");  
    17.         }  
    18.     }  
    19.   
    20.     public static void main(String[] args) {  
    21.         for (int i = 0; i < 10; i++) {  
    22.             Thread daemon = new Thread(new DaemonDemo());  
    23.             // 必须在start之前设置为后台线程  
    24.             daemon.setDaemon(true);  
    25.             daemon.start();  
    26.         }  
    27.         System.out.println("All daemons started");  
    28.         try {  
    29.             TimeUnit.MILLISECONDS.sleep(1000);  
    30.         } catch (InterruptedException e) {  
    31.             // TODO Auto-generated catch block  
    32.             e.printStackTrace();  
    33.         }  
    34.     }  
    35. }  
    36. </span>  


     

    运行结果:

    All daemons started
    #Thread-2
    #Thread-3
    #Thread-1
    #Thread-0
    #Thread-9
    #Thread-6
    #Thread-8
    #Thread-5
    #Thread-7
    #Thread-4

    分析:从结果可以看出,十个子线程并没有无线循环的打印,而是在主线程(main())退出后,JVM强制关闭所有后台线程。而不会有任何希望出现的确认形式,如finally子句不执行。

  • 相关阅读:
    概率与数学期望初步
    $Luogu$ $P4316$ 绿豆蛙的归宿(附期望 $dp$ 的设计总结)
    $Luogu$ $P4427$ $[BJOI2018]$ 求和
    $SP3978$ $DISQUERY$ $-$ $Distance$ $Query$
    最近公共祖先模板(未完待续)
    $Luogu$ $P3052$ $[USACO12MAR]$ 摩天大楼里的奶牛 $Cows$ $in$ $a$ $Skyscraper$
    $Luogu$ $P2622$ 关灯问题 $mathrm{II}$
    [转载] $CF633F$ 题解
    [转载] $Luogu$ $P3933$ 题解
    2020高考回忆录(随便写写
  • 原文地址:https://www.cnblogs.com/lingyi1111/p/4433129.html
Copyright © 2011-2022 走看看