Note that there are some explanatory texts on larger screens.

plurals
  1. POCyclicBarrier not working as expected
    primarykey
    data
    text
    <p>I am trying to simulate a triatlon competition using <code>CyclicBarrier</code> but it doesn't work as expected and I don't know why.</p> <p>Each part of the competition has to wait till all the runners have completed the previous one, but it seems like it's waiting forever.</p> <p>This is the piece of code for the phase one:</p> <pre><code>class Runner implements Runnable { private CyclicBarrier bar = null; private static int runners; private static double[] time; private int number; public static String name; public Runner(int runners, String name) { time = new double[runners]; for (int i=0; i&lt;runners; i++) time[i] = 0; this.name= name; } public Runner(CyclicBarrier bar, int number) { this.bar = bar; this.number = number; } public void run() { try { int i = bar.await(); } catch(InterruptedException e) {} catch (BrokenBarrierException e) {} double tIni = System.nanoTime(); try { Thread.sleep((int)(100*Math.random()); } catch(InterruptedException e) {} double t = System.nanoTime() - tIni; time[number] += t; } } public class Triatlon { public static void main(String[] args) { int runners = 100; CyclicBarrier Finish_Line_1 = new CyclicBarrier (runners); Runner c = new Runner(runners, "Triatlon"); ExecutorService e = Executors.newFixedThreadPool(runners); for (int i=0; i&lt;runners; i++) e.submit(new Runner(Finish_Line_1, i)); System.out.println(Finish_Line_1.getNumberWaiting()); // this always shows 99 try { int i = Finish_Line_1.await(); } catch(InterruptedException e01) {} catch (BrokenBarrierException e02) {} System.out.println("Swimming phase completed"); // here the rest of the competition, which works the same way } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload