0

In Java (Android), is there a way to create a loop that goes through a lot of operations, but only is capable of doing n amount of operations at a time?

For example, let's say I need to make 50 network operations, but only want to run, say, ten at a time, and queue the rest?

Cheers

EDIT: This is already fixed. I found a solution for my problem, but cannot close the question yet. Sorry!

Michell Bak
  • 13,182
  • 11
  • 64
  • 121

4 Answers4

1

This seems like more of a design issue than anything else. My current project requires a similar solution, and we decided to use a bounded ExecutorService to solve the problem. It may not be suitable for your particular issue, but it's worth checking out. I am also not up to speed on Android development unfortunately, so I'm not sure whether it would be a suitable solution, but check this thread.

Community
  • 1
  • 1
HalliHax
  • 816
  • 2
  • 11
  • 26
  • Hi Tom! Thanks for your suggestion - tried it, but it unfortunately doesn't implement well into my current app. My app actually needs to create a set of class instances that make the network operations, and then need to report back once they've completed. Thanks though! – Michell Bak Jul 30 '11 at 09:25
1

It sound's like you're looking for semaphores. (Basically a sort of lock, where you permit multiple threads to execute a piece of code, but no more than the allotted amount at any given time, sort of like if you have 5 bathrooms, and 10 people needing to use them, you would let the first 5 in, and the renaming 5 as space cleared up). And it looks like they're built into Java.

Leif Andersen
  • 21,580
  • 20
  • 67
  • 100
0

I managed to solve my problem using a method and some checks in it. It's kinda hard to explain, as I've made some custom stuff in the classes I'm using, but the important thing is that I solved it :)

Michell Bak
  • 13,182
  • 11
  • 64
  • 121
0

implement Runnable and assign an ID field to each object which will be the for loop index the loop queue 10 runnables and pauses check id while executing Runnable and turn a flag on

asaad399
  • 31
  • 5