Reputation: 88
I have two statements that call two methods from C++ files in the jni library in my Android app. For example -
x1 = function1();
x2 = function2();
Each of these methods take about 8 seconds to return a value (due to some data processing). My aim is to have these be executed simultaneously and not one after the other (which is causing a delay of 16 seconds).
I tried making two Runnables, but then I realized they get added to the same queue.
I don't want to extend the Thread class because I don't want these function calls to be looped (I need them to be called only when I want)
Is there a solution where I can call them both simultaneously just once and have them return their values at about the same time?
Upvotes: 2
Views: 310
Reputation: 4994
We can do that with a thread pool, no need to extend Thread
:
ExecutorService pool = Executors.newFixedThreadPool(2);
Future future1 = pool.submit(new Callable() { public Object call() { return function1(); } } );
Future future2 = pool.submit(new Callable() { public Object call() { return function2(); } } );
x1 = future1.get();
x2 = future2.get();
Upvotes: 0
Reputation: 239
You should look into Android's AsyncTask class. It provides a way to start a thread running in the background, and then provide callbacks when the work is complete. In this case both threads will run in the background, so you'll have to keep in mind that the rest of your code will keep running until the work is done, unless you tell the main thread to wait.
Upvotes: 1