6.守护线程

 Java中有两种线程,一种是用户线程,另一种是守护线程。

 当进程不存在或主线程停止,守护线程也会被停止。

 使用setDaemon(true)方法设置为守护线程

**

 *

 * 什么是守护线程? 守护线程 进程线程(主线程挂了) 守护线程也会被自动销毁.

 *

 * @classDesc: 功能描述:(守护线程)

 */

public class DaemonThread {

 

  public static void main(String[] args) {

    Thread thread = new Thread(new Runnable() {

      @Override

      public void run() {

        while (true) {

          try {

            Thread.sleep(100);

          } catch (Exception e) {

            // TODO: handle exception

          }

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

        }

      }

    });

    thread.setDaemon(true);

    thread.start();

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

      try {

        Thread.sleep(100);

      } catch (Exception e) {

 

      }

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

    }

    System.out.println("主线程执行完毕!");

  }

猜你喜欢

转载自www.cnblogs.com/goldlong/p/10953903.html
今日推荐