多线程---守护线程

守护(daemon)线程

 

 

 

package com.mokuiran.thread;

//测试守护线程

public class TestDaemon {
   public static void main(String[] args) {
       God god = new God();
       You1 you1 = new You1();

       Thread thread = new Thread(god);
       thread.setDaemon(true);//默认是false表示用户线程,正常的线程都是用户线程
       thread.start();//守护线程启动

       new Thread(you1).start();
  }
}
class God implements Runnable{

   @Override
   public void run() {
       while (true){
           System.out.println("God保护着你");
      }
  }
}

class You1 implements Runnable{

   @Override
   public void run() {
       for (int i = 0; i < 36500; i++) {
           System.out.println("活着");
      }
       System.out.println("goodbye!world!");
  }
}

//最终输出结果:
//当“活着的36500次运行完毕,那么“保护者你”也会结束线程”



 

 

 

posted @ 2022-09-17 13:57  默夔然  阅读(161)  评论(0)    收藏  举报