以前一直以為 main thread 執行結束後,在 main裡產生的 thread 也會隨之結束。
事情不是憨人想的這麼簡單啊!!!
Thread thread = new Thread(() -> {
while(true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread alive ...");
}});
//thread.setDaemon(true);
thread.start();
在 main thread 加上這段程式碼後可以發現 console 還是會一直印出 thread alive,此時 jvm 其實還活著。
執行緒有2種,User Thread 與 Daemon Thread.