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?
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.
If you wanted to notify the Phaser you have arrived but not await advance you would simply
arrive()
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.