Basically , i have 5 Runnables for each user.
Inside each Runnable, There must be waiting for a variable to change until it continues. I'll be using either a Semaphore or a CountDownLatch.
So inside each Runnable there is a runnable for waiting.
Here's an example. r1 is a runnable supposed to be user so never ending.
final Handler handler = new Handler();
Runnable r1 = new Runnable() {
@Override public void run() {
// here must be another runnable for waiting
Runnable r2 = new Runnable() {
@Override public void run() {
if (condition) {
latch.countDown();
// ending the runnable
handler.removeCallbacks(r2);
} else {
// keep waiting
handler.postDelayed(r2, 1000);
}
}
}
latch.await();
// restarting the runnable
handler.postDelayed(r1, 1000);
}
}
The problem when using latch.await()
is that is running in main thread so blocking the UI.
Any idea how to starts those runnable in different threads?
What i wanted to do is a non stop running Thread that somewhere needs to wait a variable to change so it continues other instructions. Somewhere in the UI when a button is clicked ,a semaphore gets incremented. And in the thread it waits until it is available. Here's the solution i made