1

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?

1

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.

  • 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 '14 at 10:00
0

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, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.