[Java] Daemon线程 守护线程 →→→→→进入此内容的聊天室

来自 , 2019-12-12, 写在 Java, 查看 130 次.
URL http://www.code666.cn/view/3871bd64
  1. /**
  2.  * Daemon(守护)线程 Daemon线程区别一般线程之处是:
  3.  * 只有虚拟机中的用户线程(非Daimon线程)全部结束,Daemon线程就会立即结束,并且也不会调用finally里的语句。
  4.  * daemon线程所产生的所有线程都是daemon的
  5.  */
  6. public class Daemon {
  7.  
  8.         static class MainThread extends Thread {
  9.  
  10.                 public void run() {
  11.                         System.out.println("MainThread is daemon? " + this.isDaemon());
  12.                         System.out.println("MainThread begin!");
  13.                         // 启动子线程
  14.                         Thread sub1 = new SubThread();
  15.                         // sub1线程为守护线程
  16.                         sub1.setDaemon(true);
  17.                         sub1.start();
  18.                         try {
  19.                                 Thread.sleep(1000);
  20.                         } catch (InterruptedException e) {
  21.                                 e.printStackTrace();
  22.                         } finally {
  23.                                 System.out.println("MainThread" + " finally");
  24.                         }
  25.                         System.out.println("MainThread end!");
  26.                 }
  27.         }
  28.  
  29.         static class SubThread extends Thread {
  30.  
  31.                 public void run() {
  32.                         System.out.println("SubThread is daemon? " + this.isDaemon());
  33.                         System.out.println("SubThread begin!");
  34.                         int i = 0;
  35.                         try {
  36.                                 while (i < 10) {
  37.                                         System.out.println("SubThread  " + i++);
  38.                                         Thread.sleep(200);
  39.                                 }
  40.                         } catch (InterruptedException e) {
  41.                                 e.printStackTrace();
  42.                         } finally {
  43.                                 System.out.println("SubThread finally");
  44.                         }
  45.                         System.out.println("SubThread end!");
  46.                 }
  47.         }
  48.  
  49.         public static void main(String[] args) {
  50.                 System.out.println("Main begin!");
  51.                 // 默认情况下mainThread是普通线程
  52.                 Thread mainThread = new MainThread();
  53.                 // 启动mainThread线程
  54.                 mainThread.start();
  55.                 try {
  56.                         Thread.sleep(500);
  57.                 } catch (InterruptedException e1) {
  58.                         e1.printStackTrace();
  59.                 }
  60.                 System.out.println("Main end!");
  61.         }
  62. }

回复 "Daemon线程 守护线程"

这儿你可以回复上面这条便签

captcha