为什么运行无限循环的非守护程序线程会停止?

时间:2016-01-15 13:18:11

标签: java multithreading jvm

正如我们所知,如果所有非守护程序线程都退出,JVM将停止,并且如果非守护程序线程未退出,则JVM将不会退出。但是,当我运行下面的代码时,结果似乎与我预期的不同。

public class Test{

public static void main(String[] args){

    System.out.println("start");

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true){
                System.out.println(LocalDateTime.now() + " - running");
            }
        }
    }).start();

    System.out.println("end");
    try{
        Thread.sleep(1000);
    }catch(InterruptedException e){
        System.out.println("inter");
    }
    }
}

我认为应该发生的事情是JVM不应该退出并永远输出running,但是1秒后输出停止。为什么会这样?我的理解是错误的还是我的Test课程不合适?

更新:我尝试了ps | grep java命令,但没有结果, 当我删除sleep(1000) running将永远打印出来时,我正在使用mac和java 1.8,任何人都可以告诉我为什么会发生这种情况,谢谢! enter image description here

1 个答案:

答案 0 :(得分:1)

如果我跑

import java.time.LocalDateTime;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("start");

        new Thread(() -> {
            try {
                while (true) {
                    System.out.println(LocalDateTime.now() + " - running");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(1000);
        System.out.println("end");
    }
}

我得到了

start
2016-01-15T08:30:58.378 - running
2016-01-15T08:30:58.889 - running
end
2016-01-15T08:30:59.389 - running
2016-01-15T08:30:59.890 - running
2016-01-15T08:31:00.391 - running
2016-01-15T08:31:00.892 - running
2016-01-15T08:31:01.392 - running
2016-01-15T08:31:01.893 - running
2016-01-15T08:31:02.394 - running
... many more