• 后台线程


    package com.roocon.thread.t2;
    
    public class Demo1 extends Thread {
    
        public Demo1(String name){
            super(name);
        }
    
        @Override
        public void run() {
            try{
                while(true){
                    System.out.println(getName()+"线程执行了");
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }finally {
                System.out.println("finally不会被后台线程执行");
            }
        }
    
        public static void main(String[] args) {
            Demo1 d1 = new Demo1("first-thread");
            Demo1 d2 = new Demo1("second-thread");
            d1.setDaemon(true);
            d2.setDaemon(true);
            d1.start();
            d2.start();
            System.out.println("main方法执行即将结束");
        }
    }

    输出结果:

    main方法执行即将结束
    second-thread线程执行了
    first-thread线程执行了

    对以上代码的解释:

    在main方法中,main为主线程,当主线程执行完输出语句时,cpu被second-thread和first-thread抢去执行了,当main主线程再次抢的cpu执行时,发现main方法中已经没有需要执行的代码,故main方法结束。然后,由于second-thread和first-thread都为后台线程,于是,随着主线程的运行完毕而立马结束。

    作者:凌晨六点半
    出处:http://www.cnblogs.com/sunnyDream/

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。 如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能 打赏我一杯咖啡【物质支持】,也可以点击右下角的【好文要顶】按钮【精神支持】,因为这两种支持都是我继续写作,分享的最大动力!

  • 相关阅读:
    Thomas Hobbes: Leviathan
    10 Easy Steps to a Complete Understanding of SQL
    day3心得
    py编码终极版
    day2 作业
    Python 中的比较:is 与 ==
    day2-心得
    day1--心得
    day1作业
    python--open用法
  • 原文地址:https://www.cnblogs.com/sunnyDream/p/7995425.html
Copyright © 2020-2023  润新知