How can I coordinate two background tasks? How can I coordinate two background tasks? multithreading multithreading

How can I coordinate two background tasks?


Is it really difficult to determine this without seeing your code. One dirty solution would be to add a static boolean and then add a recursive timer. This is not the best programming technique, but from what I read it would certainly work.

Create a static boolean in any class

static boolean onPostExecuteFinished;

in the the AsyncTask that needs to be finished first set it to true

ClassName.onPostExecuteFinished = true;

In the class that needs to wait you make a recursive method waiting for it to finish. I recommend using a handler.

public void nameOfRecursiveMethodHere()Handler handler = new Handler()handler.postDelated(new runnable........{if (ClassName.onPostExecuteFinished) {//Great it is finished do what you need} else {//Not finished call this method againnameOfRecursiveMethodHere();}}),(put how often you want it to check in milliseconds here);


Rather than using 2 AsyncTasks I would suggest to use RxJava and RxAndroid. Concurrency is done much easier there.

For example you can do the following to sync your async Jobs:

Observable<Object1> job1 = Observable.fromCallable(() -> yourCall2());Observable<Object2> job2 = Observable.fromCallable(() -> yourCall2());Observable.combineLatest(job1, job2, (object1, object2) -> yourMethod())    .subscribeOn(Schedulers.io())    .observeOn(AndroidSchedulers.mainThread())    .subscribe(...);

This is only a small, incomplete example but should show how to achieve what you want. I've used Lambda Expressions to shorten the Code. This is done by using Retrolambda. You can achieve the same with the zip Operator.


As @Andy-Turner commented, using a CountDownLatch is possible, also you can use a Semaphore to signal the execution of a task from another.

please check this link:http://tutorials.jenkov.com/java-concurrency/semaphores.html