Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 774
aguagu Avatar asked Feb 28 '26 08:02

aguagu


1 Answers

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.

like image 147
GhostCat Avatar answered Mar 02 '26 22:03

GhostCat