zoukankan      html  css  js  c++  java
  • Java多线程-守护线程

    1、在Java 中有两种线程,一种是用户线程,二是守护线程( Daemon )

    2、守护线程的定义

      守护线程是一种特殊的线程,他的特性有陪伴的含义,当进程中不存在非守护线程了,则守护线程自动销毁。典型的守护线程就是垃圾回收线程。

    3、示例:

    public class DaemonTest {
        public static void main(String[] args) {
            try {
                MyThread thread = new MyThread();
                thread.setDaemon(true);
                thread.start();
                Thread.sleep(5000);
                System.out.println("我离开 thread 对象就不再打印了,也就是停止了");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        static class MyThread extends Thread {
            private int i = 0;
    
            @Override
            public void run() {
                try {
                    while (true) {
                        i ++;
                        System.out.println("i =  " + (i));
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    运行结果如下:

  • 相关阅读:
    python time 转换&运算tips
    Web.py session用户认证
    简单的内存池实现gko_alloc
    cpp(第十章)
    cpp(第九章)
    cpp(第八章)
    cpp(第七章)
    cpp(第六章)
    cpp(第五章)
    结构中的位字段
  • 原文地址:https://www.cnblogs.com/lkc9/p/12451991.html
Copyright © 2011-2022 走看看