zoukankan      html  css  js  c++  java
  • java基础---->多线程之Daemon(五)

      在java线程中有两种线程,一种是用户线程,另一种是守护线程。守护线程是一种特殊的线程,当进程中不存在非守护线程了,则守护线程自动销毁。今天我们通过实例来学习一下java中关于守护线程的知识。我是个平常的人,我不能盼望在人海中值得你一转眼的注意。

    java中守护线程的例子

    一、java中守护线程的简单使用

    package com.linux.thread;
    
    import java.util.concurrent.TimeUnit;
    
    public class MyThread extends Thread {
        private int i = 0;
    
        @Override
        public void run() {
            try {
                while (true) {
                    i++;
                    System.out.println("i = " + i);
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    测试的主体类的内容如下:

    package com.linux.thread;
    
    import java.util.concurrent.TimeUnit;
    
    public class MyThreadRun {
        public static void main(String[] args) {
            try {
                MyThread thread = new MyThread();
                thread.setDaemon(true);
                thread.start();
                TimeUnit.SECONDS.sleep(5);
                System.out.println("Liberty consists in doing what one desires."); // 当主线程执行这完毕,守护线程就停止执行。
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    一次的运行结果如下:

    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    Liberty consists in doing what one desires.

    当主线程执行完毕被销毁之后(所有的非守护线程执行完成之后),所有的守护线程被自动销毁。

    友情链接

  • 相关阅读:
    User-agent大全
    获取https
    python 异常类型
    Git之生成ssh公钥
    Git 笔记
    iptables
    如何在CentOS 6.4上安装并使用OpenVZ?
    centos6.5 pptpd
    CentOS 6.x安装Metasploit
    CentOS 6.5下安装BeEF
  • 原文地址:https://www.cnblogs.com/huhx/p/baseusejavathreadDaemon.html
Copyright © 2011-2022 走看看