CyclicBarrier sample code
程序员文章站
2022-07-14 12:47:44
...
Runnable version of Solver sample code in CyclicBarrier's javadoc.
import java.util.concurrent.*;
public class Solver {
final int N;
final float[][] data;
final CyclicBarrier barrier;
class Worker implements Runnable {
int myRow;
Worker(int row) { myRow = row; }
@Override
public void run() {
processRow(myRow);
try {
barrier.await();
} catch (InterruptedException ex) {
return;
} catch (BrokenBarrierException ex) {
return;
}
}
}
private final void processRow(int row) {
for (int i = 0; i < N; i++)
data[row][i]++;
}
private final void mergeRows() {
for (int j = 0; j < N; j++) {
int sumOfRows = 0;
for (int i = 0; i < N; i++)
sumOfRows += data[i][j];
System.out.println("sum of rows in column " + (j + 1) + ": " + sumOfRows);
}
}
public Solver(float[][] matrix) throws InterruptedException, BrokenBarrierException {
data = matrix;
N = matrix.length;
barrier = new CyclicBarrier(N,
new Runnable() {
@Override
public void run() {
mergeRows();
}
});
for (int i = 0; i < N; ++i)
new Thread(new Worker(i)).start();
}
public static void main (String [] args) throws Exception {
float[][] m = {{11, 12, 13},
{21, 22, 23},
{31, 32, 33}};
Solver s = new Solver(m);
}
}
推荐阅读
-
解决Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-f8IeEI/MYSQL-python/
-
CountDownLatch(闭锁)、Semaphore(信号量)、CyclicBarrier
-
Entity Framework Code First属性映射约定
-
记录微信支付开发中的小经验(errcode = 40163; errmsg = "code been used")
-
利用Typings为Visual Studio Code实现智能提示功能
-
Java并发系列之CyclicBarrier源码分析
-
全新Visual Studio Code预览版0.10.10发布下载
-
Let's Code
-
ubuntu下VS code如何调试C++代码
-
并发编程(二)—— CountDownLatch、CyclicBarrier和Semaphore