Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for threads to complete before continuing

When the user launches my Android App, I fire up 2 threads to do some processing in the background. thread_1 does some calculations on the client, and thread_2 fetches some data from the server. That all works fine. None of the threads modify the UI. I have two follow up questions.

new Thread(new Runnable(){
    @Override
    public void run(){
        MyClass.someStaticVariable = doSomeCalculations();
    }
}).start();
  1. What is the best practice to retrieve the data from the run() method of a thread? I currently have a static variable, and I assign the relavent calculated data/ fetched data to it. Or is it recommended to use the Handler class to get data out of threads? I imagined one only uses the handler if they wish to update the UI.

    while(true)
    {
        if (!thread1.isAlive() && !thread2.isAlive())  
        {
            startActivity(intent)
        }
    }
    
  2. I need to wait until both threads are finished before I can pass the data from both threads via an Intent. How can I achieve that? I can do it using the code shown above, but that just seems wrong.

like image 366
Raunak Avatar asked Sep 22 '11 17:09

Raunak


1 Answers

Using callable / Future / ExecutorService would be the cleanest way of doing this in a reqular java app (should be same for android as well)

ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> firstThreadResult = executor.submit(new Callable<Integer>() {
   Integer call() {
   }
});

Future<Integer> secondThreadResult = executor.submit(new Callable<Integer>() {
   Integer call() {
   }
});

executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE,TimeUnit.SECONDS); // or specify smaller timeout
// after this you can extract the two results
firstThreadResult.get();
secondThreadResult.get();

More detailed example.

like image 76
gkamal Avatar answered Oct 28 '22 12:10

gkamal