I have a situation here, where I have a loop that loops x amount of times. The value x is determined by the user. Everytime it loops, I want it to wait for a button click before continuing the loop. ie. something like this (pseudocode):
loop(x times){
Button b;
wait until a click
when clicked{
b.onclicklistener{
setText(x);
}
}
}
I am using this for an android app, so with Thread.wait()/Thread.notify() what I learned was that it interrupts the main UIthread, so I cannot use that.
So what I believe the only two options that I can use to kind of “pause” the loop is CountDownLatch.await() or AsyncTask (I don’t know what that does, have not researched about it)
Would CountDownLatch.await()/CountDownLatch.countDown() be the best methods and class to use in this example, or should I look into AsyncTask?
Instead of thinking of it as the button “unpausing” a loop, I would prefer to think of it as something running every time you click the button, like:
b.onclicklistener {
return (or remove listener) if loops > x
loops++
setText(x)
restOfLoop()
}
That being said, if you absolutely require your loop to run in a separate thread, a regular Semaphore
would suffice in your situation. Just call acquire()
in the loop where you want it to pause, and release()
in the click listener.
1
I wouldn’t use CountDownLatch
in your scenario because it’s not reusable. Look at Semaphore
or Cyclic Barrier
for similar functionality.