我想让主线程保持 Activity 状态。 我找到了 3 个选项,我想知道哪一个是最好的。 有什么区别,为什么?
其中有没有浪费资源的情况?
while(true){}
thread.join()
CountDownLatch(1).await()
我尝试过,效果很好。
while(true){}
thread.join()
CountDownLatch(1).await()
最佳答案
这里:
while(true){}
进行“热”等待。这意味着:您的 CPU 以 100% 的速度旋转,什么也不做。也许,也许,如果你真的很幸运,JVM 会检测到这一点,并且能够不那样消耗 CPU 周期。
对于 join(),我们发现:
When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.
(来自此tutorial)
所以,join() 听起来是更健康的方法。 await()
应该以类似的方式工作。
这两种方法的缺点:它们对线程中断使用react,因此将它们放入“while true”循环中可能是个好主意。
关于java - while(true) 和 wait() 或线程 join() 之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56234461/