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{

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?

2 Answers 2


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

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.

  • This is definitely a better approach. Just commenting to add that CountDownLatch.await has the same problem as an ordinary "wait" method: it blocks the current thread, and it sounds like your loop is in the main thread, so you really shouldn't do that. AsyncTask is probably the easiest way to get your code running in another thread, if you decide to go that way.
    – Jules
    Dec 12, 2014 at 10:00

I wouldn't use CountDownLatch in your scenario because it's not reusable. Look at Semaphore or Cyclic Barrier for similar functionality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.