简体   繁体   中英

CountDownLatch.await() suspending background threads

I'm working on an android app which at some point runs a service. That service runs a new thread for a time-consuming operation and waits for a countDownLatch to be zero. After that it runs a second thread for another time-consuming operation (that new thread isn't really necessary now but will be in the near future).

Now...after starting the downloadThread, if I do the waiting as shown below, the main thread AND the downloadThread suspend operations. However, if I wait for the countDownLatch inside the uploadThread everything works fine.

Thread downloadThread = new Thread(new Runnable() {
 @Override
 public void run() {
   downloadFiles(mMediaFileList);
 }
});

downloadThread.start();

try {
 Log.d("UploadMedia", "Waiting for DownloadMedia to finish");
 mCountDownLatch.await();
} catch (InterruptedException e) {
 e.printStackTrace();
}

Thread uploadThread = new Thread(new Runnable() {
 @Override
 public void run() {
  uploadMedia();
 }
});

uploadThread.start();

It's not really a problem but isn't it supposed to work both ways? Is there something I'm missing about the .await() functionality?

Cheers!

Edit: FYI, downloadFiles has callbacks which wait for completion or failure of the task. Can it be that those callbacks work on the main thread which is being suspended by the .await()?

It's not evident where your latch gets count down. But it sounds as it happens during uploadMedia(). If so, your main thread gets stale at latch.await() because there is no other controlflow that could count the latch down to zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM