开发者

Execute simultaneous threads and notify when the last ends (Android Java)

My program have: One Activity One heavy task to do when a button is pressed (with many threads cause are 10 download). So when the button is presed I show a progress dialog and I do

onClick(){
  showDialog();
  for (int i=0;i<10;i++)
       download(i);   //download launches a new thread each call
  //wait without blocking the UI thread until last downlo开发者_运维技巧ad end
       continue();
}

Whats the best and easier way of doing that? Thanks so much in advance


You'll need references to all the 10 Thread objects. Say as an Array Thread [] tasks

so, you need to call the join() function to wait (blocking) for the thread to end.

for(int i = 0 ; i < 10; i++)
      tasks[i].join();


You could use a CountDownLatch or a CyclicBarrier.

You create the CountDownLatch, and initialize it with the number of threads you are starting, then pass it into each download thread. When the download thread is done its work, it calls countDown on the latch.

You can either call await on the latch from within the onClick method (but that will block that thread, which sounds like you don't want to do), or spawn one extra thread that simply calls await, blocking waiting for all of the download threads. Once the latch is opened, you can perform whatever actions you need to do (eg, take down the progress dialog).

final CountDownLatch latch = new CountDownLatch(10);
for (int i=0;i<10;i++)
    download(i, latch);

Thread cleanup = new Thread( new Runnable() {
    public void run() {
        try{
            // This will block
            latch.await();
        } catch (InterruptedException e ) {
            // TODO
            e.printStackTrace();
        }
        takeDownDialog();
        whateverElseYouNeedToDo();
    }
});
cleanup.start();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜