0

For my homework I have to make a game of several kings moving across the chess board. Each king must move from his unique starting to unique ending position in own thread. Before making his move king must sleep for up to 10 milliseconds (a bit of randomness) then wait for others to make their moves.

I've solved the problem of kings waiting for each other to make a move with CyclicBarrier, but the problem arises when one of the kings gets to his ending position thus stopping his own thread. The CyclicBarrier is then waiting for the thread to call the await() method but that never happens since the thread isn't running anymore.

Any suggestions?

Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
  • There's no way to directly accomplish what you want with the java.util.concurrent.CyclicBarrier class. You might be able to tweak the kings' logic so that a CyclicBarrier still helps you out, however. – Sbodd Jun 08 '12 at 14:07
  • Have you considered making a subclass of `CyclicBarrier` with an additional method - perhaps `gone` would be appropriate - which merely spawns a thread that takes over the functionality of the quitting thread by just `await`ing in a loop? That's certainly how I would approach this. – OldCurmudgeon Jun 08 '12 at 23:48

1 Answers1

1

Yes. Use a Phaser that comes with Java 7. It is an advanceable CycliclBarrier.

To mimic a CyclicBarrier directly you would use the Phaser this way.

Phaser phaser = new Phaser(n);

public void doWorkAndAwait(){
   //work
   phaser.arriveAndAwaitAdvance(); //await for all threads to arrive
}

If you wanted to notify the Phaser you have arrived but not await advance you would simply arrive()

public void doWorkAndContinue(){
   //work
   phaser.arrive();
   //stop own thread
}

At this point the Phaser has been notified that the thread has arrived but the thread can stop own thread without having to wait for the other threads to arrive.

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • Thanks. I'll take a look at the Phaser class. The only problem I see with it it's that it was introduced in Java 7. Unfortunately I think our assistants still use Java 6. – Tjaz Brelih Jun 08 '12 at 14:38
  • No problem. That's a shame, this will accomplish exactly what you're looking for. – John Vint Jun 08 '12 at 14:45