为什么非守护线程运行 无限循环停止?
Why does a non-daemon thread running an infinite loop stop?
众所周知,如果所有非守护线程退出,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 秒后输出停止。为什么会这样?是我的理解有误还是我的测试 class 不合适?
更新:我试过命令ps | grep java
,但没有结果,
当我删除 sleep(1000)
时 running
将永远打印出来,我正在使用 mac 和 java 1.8,任何人都可以告诉我为什么会这样,谢谢!
如果我运行
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
众所周知,如果所有非守护线程退出,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 秒后输出停止。为什么会这样?是我的理解有误还是我的测试 class 不合适?
更新:我试过命令ps | grep java
,但没有结果,
当我删除 sleep(1000)
时 running
将永远打印出来,我正在使用 mac 和 java 1.8,任何人都可以告诉我为什么会这样,谢谢!
如果我运行
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