Executing Threads in a queue

Hello everybody, I enjoyed the Game Loops tutorial on this board, but I have a slightly different problem, so I decided to post.

I have 10 balls-Threads, and I need every one of them to move once, then wait for the others to move before it can
move again. Sounds awful, it is awful, but please bear with me. I’ll design it better next time.

If the 10 balls were not Threads, moving them one by one would be as simple as selecting then in a for loop.
Since I screwed it up, now it’s a synchronization nightmare, and I’d like the simplest of the solutions, if you have one, to make
those threads run the way I want.

The balls can move like this
turn 1) 1, 2, 3, 4, 5, …, 10
turn 2) 10, …, 5, 4, 3, 2, 1
turn 3) 2, 1, 3, 5, 4, …, 10

But not like this
turn 1) 2, 2, 1, 3, 3, 3, …, 10

BTW I tried searching round-robin on Google, and I found some simulations of a real scheduler, so let me make this clear
I do not need a quantized time (some thread can take more time than the others to execute)
I do not need absolute timing (maybe it can help, but if your solution is simpler without, then it’s better without)

EDIT: see this post for further informations (and a different example)

Make your balls not Threads! :wink:

Don’t use threads in this way!!!

If you want to bury yourself deeper, you can use a CyclicBarrier, http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html

Thank you, this CyclicBarrier could be useful.

Now I have a little problem. What if one of the balls dies?

Then I need to change the N of the CyclicBarrier, but so far I can’t see a way of doing this.

I’m looking at the CountDownLatch class, but after literally hours I can’t figure out how to make it work.

Let’s take the Driver-Worker example of the Java doc:

  • I need those Workers to work once a day for 4 days,
  • Some Workers can resign before the 4th day is over.
  • I need the rest of them to keep working on, once a day till the 4th day

I put the CountDownLatches in the Driver. The Workers read them through the Driver.
I need to recreate them at the start of every day.
If I recreate them too soon, some Worker will not be able to read the old value and awake. (big problem)

I tried to modify the code of the example, but I can’t get it to work.

Seriously, why are you trying to use threads for this? You’re just digging yourself deeper into pain. Do it the regular way and just store your balls in one collection and update them all from one thread.

Ok, balls or not, now I’m curious about the Driver-Workers problem.

I’d like to learn some new option for concurrency, probably it’s not the best option this time, but could turn out useful next time.

The number of parties in a CyclicBarrier is fixed on construction. If you remove parties, you need a new barrier. A CountDownLatch is more appropriate to being recreated every iteration, but it’s not all that useful for synchronous parts since you can’t control which thread is the one that blocks on the rest.

If you really must multithread this, I think you’re looking for an ExecutorService. You submit each ball’s task to the Executor, invokeAll() on them, then wait on all the futures (just loop over them, there’s no built-in join functionality for lists of Futures per se).

I have to concur with the others here though, threading this is really just digging yourself in deeper. The moment the balls need to interact, you’ll really find yourself in hell.

btw - didn’t notice your username when I first posted. If that’s what you’re trying to create, you’re going the right way! :stuck_out_tongue:

As others have commented on it, but not knowing more on your particular use case you likely don’t need threads. As Sproingie mentioned you’ll want to check out ExecutorService and the related APIs. You can build up your own API around it to control how things get run. I have a custom API built on it in my efforts that allows (of course in a component oriented fashion) to feed one thread pool in several different manners. Basic (one or more threads run immediately depending on available slots in the thread pool), Single (all threads submitted run single file), Pending (a runnable is submitted and will run as soon as a slot is open, if a new runnable is submitted it will wait in a pending state and run after any currently active runnable. If a new runnable is submitted while a pending one is waiting the pending one is replaced; good for long running GUI actions connected to something the user can press many times repeatedly. Such that the first and last button press will only potentially trigger execution). One can add a new custom scheduling mechanism too and have it share a thread pool.

I used a custom executor service when rewriting the download queue of the Amazon MP3 Android app that when the current download is paused it pushes the current download to the front of a custom BlockingQueue thus when the user resumes it pulls the previously downloading item and makes it active again. So you can certainly control the way runnables are scheduled and even service multiple ways of scheduling them from one thread pool. ExecutorService is also cross-platform between J2SE and Android. There really is no reason to use AsyncTask on Android when you can accomplish things in a cross-platform way via ExecutorService.

It’s not in my intentions to be such a masochist, but I have to deal with some “requests”.

I don’t know, the Executor looks complicated. Please forget the balls and look at this:

Driver-Worker example of the Java doc:

  • I need those Workers to work once (and only once) a day for 4 days,
  • Some Workers can resign before the 4th day is over.
  • I need the rest of them to keep working on, once a day till the 4th day

Would it be possible to destroy a CyclicBarrier, recreate it (and update the Workers’ references) in its Runnable() ?
Or is it better to use an Executor?

Threading is complicated, and you can’t take shortcuts. And as someone who has done plenty of threading before, I personally find CyclicBarrier to be complicated, and ExecutorService to be the height of simplicity. Callables go in, Futures come out. Easy peasy.

When you say four days, do you really mean four real actual days, or simulated days that take a few seconds? If your task scheduling is at the granularity of days, you should probably schedule them with something like Quartz (which I’ll admit is a bit complicated to start with, sorry) and have them check in every once in a while to a database or a file.

I’ve only skimmed, but am I smelling actor model?

Actors are great, I love actors, I’m switching everything in my work projects to use Akka actors. And while they solve the low levels of synchronization by being message-based, they won’t really do anything for the overall design of this system except complicate it further.

I mean simulated (not real hours), just print 1 time its “hello I’m worker #1 worked a day”

So, I have a Driver, and, say, 3 workers. I want this output

//day 1
“hello I’m the driver and I’m starting my turn” //some settings
“hello I’m worker #1 and I worked a day”
“hello I’m worker #2 and I worked a day”
“hello I’m worker #3 and I worked a day”
“hello I’m the driver and I’m finishing my turn”

//day 2
“hello I’m the driver and I’m starting my turn” //some settings
“hello I’m worker #1 and I worked a day”
“hello I’m worker #2 and I worked a day”
“hello I’m worker #3 and I worked a day. I RESIGN!”
“hello I’m the driver and I’m finishing my turn”

//day 3
“hello I’m the driver and I’m starting my turn” //some settings
“hello I’m worker #1 and I worked a day. I RESIGN!”
“hello I’m worker #2 and I worked a day”
“hello I’m the driver and I’m finishing my turn”

//day 4
“hello I’m the driver and I’m starting my turn” //some settings
“hello I’m worker #2 and I worked a day”
“hello I’m the driver and I’m finishing my turn. I’M FIRING YOU ALL!”

//day 5
no worker shall work //could I use some interrupts?

This is an example that came up to my mind.
I could make it worse so that the driver fires everybody on day 2 and every worker has to resign before working another day.

I don’t know what a Future is and I’m afraid I don’t know exactly what a Task is either. Lots of new classes here.

There are a lot of examples using Executor for a server, I hope you can point me to a simple non-distributed one.

EDIT: sorry, quoted my own post, instead of fixing a typo

This. So this.

Also, this would be a heck of a lot easier if you’d actually tell us what you’re really trying to do, rather than coming up with half-baked toy examples. Because I really, really, can’t see any reason why you should even have touched any multithreading here at all.

Ok, I need an example that can do the print the kind of things that I wrote above (worker - driver).

Somebody wants me to do this stupid kind of printing/bouncing with threads. I hope you get it.

Anyway, I’m sure that there is some way this could turn out to be useful. I’m learning something new, after all.

Now I just have to print things in an ordered fashion. I know it’s simple, but I have to do it with threads.

EDIT: I’ve read some more about the Executor. My Workers are Runnables, but I have loop in them (4 days of work), and so I’m worried that submitting them and then waiting for the completion of the loop, could lead to results like

“hello I’m worker #1 and I worked a day”
“hello I’m worker #1 and I worked a day”
“hello I’m worker #1 and I worked a day”
“hello I’m worker #2 and I worked a day”

Maybe there’s some way to monitor (and pause) the progress of the submitted runnables, but I don’t get how.