Manoj Kumar Manoj Kumar - 6 months ago 22
Android Question

Using while(true) a better approach to introduce wait in android background threads

How to make a thread wait till another thread has completed its execution in java?
Using while(true) will introduce wait. But is it a good programming practice?

But will it heat up the phone?

spa spa
Answer

I would use a count down latch (here some pseudo code - meaning I did not compile or run it, it's just for giving an idea).

// create the count down latch and initialize it to 1 as we wait for one background thread to finish
final CountDownLatch cdl = new CountDownLatch(1);

// Start the background thread and give it a reference to the count down latch
final Thread thread = new Thread(new Runnable {
   public void run() {
     try {
       // do work here
     } finally {
       cdl.countDown();
     }
   }
}
thread.start();

// We wait till the background thread completes
cdl.await();

The benifit is, that is quite high level and we can wait also for multiple things by using different counts.

Comments