what is difference between while(true) and wait() or thread join()

aguagu :

I want to keep the main thread alive. I found 3 options, and i wonder which one is the best. what are the differences, and why??

is there any wasting resource among them?

  1. while(true){}

  2. thread.join()

  3. CountDownLatch(1).await()

I tried them, and those worked well.

while(true){}

thread.join()

CountDownLatch(1).await()
GhostCat salutes Monica C. :

Here:

while(true){}

does a "hot" wait. It means: your CPU spins at 100%, doing nothing. Maybe, maybe, if you are really lucky, the JVM detects that and is able to not burn CPU cycles like that.

Whereas, for join(), we find:

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.

( from this tutorial )

So, join() sounds like the more healthy approach. await() should work in similar ways.

The downside of these two methods: they react to thread interrupts, so it might probably a good idea to put them into a "while true" loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111839&siteId=1