Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

多线程中,何时主线程会等待子线程运行完才退出,何时主线程不等待子线程运行完就退出呢?

image.png

如图有3段启动线程的代码,经过测试,只有第一段代码启动的线程主线程不会等,第二种要等new的线程代码执行完毕程序才会退出,第三段是线程池也不会退出。

想请教这是为什么呢,尤其第一种写法不理解为什么主线程不会等他执行完呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

线程分daemon线程user(或者非daemon)线程
当所有线程都是daemon线程的时候jvm会退出
CompletableFuture.supplyAsync默认用的线程池都是daemon线程,所以主线程结束后jvm退出
new Thread()不设置setDaemon(true)user线程,要运行结束jvm才可以退出
Executor默认也是user线程,要运行结束jvm才可以退出


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...