JAVA 对守护线程的理解

1、在start之前,setDaemon。 该现场就成为守护线程了。

2、守护现线程并不是主线程结束,子线程(守护线程)也跟着结束。而是守护线程在没有用户线程运行的情况伴随着JVM退出而结束。

示例代码:

public class Demo {

 public static void main(String[] args) {

     //守护现线程并不是主线程结束,子线程(守护线程)也跟着结束。而是守护线程在没有用户线程运行的情况伴随着JVM退出而结束。

  MyMainThread my=new MyMainThread();

  Thread thread=new Thread(my);

  thread.start();

        for(int i=0;i<20;i++) {

   System.out.println("我是主程序,我依旧坚挺");

       try {

    Thread.sleep(200);

   } catch (InterruptedException e) {

    // TODO 自动生成的 catch 块

    e.printStackTrace();

   }   }

     } }

//主线程

class MyMainThread implements Runnable{

 @Override  public void run() {  

  MyThread my=new MyThread();

  Thread tt=new Thread(my);

  tt.setDaemon(true);  //设置为守护线程   tt.start();

  for(int i=0;i<10;i++) {

   System.out.println("我是主线程。。。。。。。。。");

   try {

    Thread.sleep(200);

   } catch (InterruptedException e) {

    // TODO 自动生成的 catch 块

    e.printStackTrace();

   }

  }

 }

}

//子线程(守护线程)

class MyThread implements Runnable{

 @Override  public void run() {

  while(true) {

   System.out.println("我是子线程,我正在运行-----------------------------");

   try {

    Thread.sleep(200);

   } catch (InterruptedException e) {

    // TODO 自动生成的 catch 块

    e.printStackTrace();

   }

  } 

    }

  }

posted @ 2019-03-01 14:02  愚钝的Tom  阅读(301)  评论(0编辑  收藏  举报