我正在尝试使用CyclicBarrier模拟三项全能比赛,但是它没有按预期工作,我也不知道为什么。

比赛的每个部分都必须等到所有跑步者完成上一个比赛为止,但是似乎它一直在等待。

这是第一阶段的代码:

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<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<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
}
}

最佳答案

一旦所有各方都呼叫await并且打开屏障,CyclicBarrier就会循环。由此得名。
因此,如果您创建具有5个参与方的呼叫并且有6个await呼叫,则最后一个呼叫将触发它再次等待另外4个参与方加入。

这基本上就是这里发生的事情,因为您的主目录中有1个额外的await调用。它正在等待另一个Runner-1通话发生。

简单的解决方法是创建带有跑步者+1派对的CyclicBarrier

10-06 15:58