Exclude a specific thread from CyclicBarrier

189 views Asked by At

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?

1

There are 1 answers

2
John Vint On BEST ANSWER

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.