Reputation: 81
I've just started using threads in Android java. I'm launching a thread from my main activity, but I need to be sure it has completed before continuing with the main logic flow.
The code is:
MyClass myclass = new MyClass();
new Thread() {
public void run() {
myclass.myMethod(); // Do some work here
}
}.start();
// More work here which assumes myMethod() has completed
The work in myMethod involves a url call, so it might take a few seconds and I need to be sure it's complete before continuing. Can anybody suggest the best way to do this? Many thanks
Upvotes: 0
Views: 42
Reputation: 288
You can use CountDownLatch:
CountDownLatch latch = new CountDownLatch(1); // create latch object with counter set to 1
new Thread() {
public void run() {
myclass.myMethod(); // Do some work here
latch.countDown(); // decrement counter from 1 to 0
}
}.start();
latch.await(); // await until counter in latch reaches 0
You should also consider using some library for handling async operations in Android like rxJava or AsyncTask.
Upvotes: 1