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子句不执行。

  • 相关阅读:
    try? try! try do catch try 使用详解
    Swift Write to file 到电脑桌面
    NSLayoutConstraint 使用详解 VFL使用介绍
    automaticallyAdjustsScrollViewInsets 详解
    Swift 给UITableView 写extension 时 报错 does not conform to protocol 'UITableViewDataSource'
    OC Swift中检查代码行数
    Swift中 @objc 使用介绍
    SWift中 '?' must be followed by a call, member lookup, or subscript 错误解决方案
    Swift 中 insetBy(dx: CGFloat, dy: CGFloat) -> CGRect 用法详解
    求1000之内所有“完数”(注:C程序设计(第四版) 谭浩强/著 P141-9)
  • 原文地址:https://www.cnblogs.com/sand-tiny/p/3962897.html
Copyright © 2011-2022 走看看