CyclicBarrier 可以通过 ORDER 指定线程:
如您所说,如果您将屏障完成逻辑包含在特定于线程索引的条件中,则可以指定以特定顺序返回的线程。因此,您的上述实现将根据您引用的文档进行。
但是,这里的混淆点是文档是根据返回屏障的顺序来讨论线程标识,而不是线程对象标识。因此,线程 0 指的是第 0 个要完成的线程。
替代方案:使用其他机制指定线程。
如果您希望在其他工作完成后让特定线程执行特定操作,您可以使用不同的机制 - 例如 semaphore 。如果你想要这种行为,你可能并不真的需要循环障碍。
要检查文档的含义,请运行下面的类(从 http://programmingexamples.wikidot.com/cyclicbarrier 修改),我在其中合并了您的 sn-p。
CyclicBarrier 文档的含义示例
包线程;
导入 java.util.concurrent.BrokenBarrierException;
导入 java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample
{
private static int matrix[][] =
{
{ 1 },
{ 2, 2 },
{ 3, 3, 3 },
{ 4, 4, 4, 4 },
{ 5, 5, 5, 5, 5 } };
static final int rows = matrix.length;
private static int results[]=new int[rows];
static int threadId=0;
private static class Summer extends Thread
{
int row;
CyclicBarrier barrier;
Summer(CyclicBarrier barrier, int row)
{
this.barrier = barrier;
this.row = row;
}
public void run()
{
int columns = matrix[row].length;
int sum = 0;
for (int i = 0; i < columns; i++)
{
sum += matrix[row][i];
}
results[row] = sum;
System.out.println("Results for row " + row + " are : " + sum);
// wait for the others
// Try commenting the below block, and watch what happens.
try
{
int w = barrier.await();
if(w==0)
{
System.out.println("merging now !");
int fullSum = 0;
for (int i = 0; i < rows; i++)
{
fullSum += results[i];
}
System.out.println("Results are: " + fullSum);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
/*
* public CyclicBarrier(int parties,Runnable barrierAction)
* Creates a new CyclicBarrier that will trip when the given number
* of parties (threads) are waiting upon it, and which will execute
* the merger task when the barrier is tripped, performed
* by the last thread entering the barrier.
*/
CyclicBarrier barrier = new CyclicBarrier(rows );
for (int i = 0; i < rows; i++)
{
System.out.println("Creating summer " + i);
new Summer(barrier, i).start();
}
System.out.println("Waiting...");
}
}