package com.zhoubo.concurrent.barrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* barrier使得所有的线程执行到barrier相互等待,直到最后一个线程。barrierAction由最后一个线程执行到barrier时候执行
*
* 其实各个线程只是执行到barrier处,线程内容不一定执行结束了。
*
* 等到最后线程执行到barrier处,没有执行完成的内容继续执行。
* @author Administrator
*
*/
public class Solver {
final int N;
final float[][] data;
final CyclicBarrier barrier;
boolean done=false;
class Worker implements Runnable {
int myRow;
Worker(int row) {
myRow = row;
}
public void run() {
// while (!done()) {
processRow(myRow);
System.out.println("waiting thread nubmer =" + barrier.getNumberWaiting());
System.out.println("barrier isBroken = " + barrier.isBroken());
System.out.println("parties = " + barrier.getParties());
try {
barrier.await();
System.out.println("render row [" +myRow +"]");
} catch (InterruptedException ex) {
return;
} catch (BrokenBarrierException ex) {
return;
}
// }
}
}
public void processRow(int row){
// int temp = 3/(row-2);
System.out.println("process row " + row);
}
public boolean done(){
return done;
}
public void mergeRows(){
// System.out.println(barrier.getNumberWaiting());
System.out.println("merge...");
// barrier.reset();
}
public void waitUntilDone(){
done = true;
}
public Solver(float[][] matrix) {
data = matrix;
N = matrix.length;
barrier = new CyclicBarrier(N
,new Runnable() {
public void run() {
mergeRows();
}
}
);
for (int i = 0; i < N; ++i)
new Thread(new Worker(i)).start();
// waitUntilDone();
}
/**
* @param args
*/
public static void main(String[] args) {
float [][] matrix = {{1.0f,2.0f},{3.0f,4.0f},{1.0f,2.0f},{3.0f,4.0f}};
Solver sl = new Solver(matrix);
}
}
CyclicBarrier理解
最新推荐文章于 2024-08-16 23:08:28 发布