Java CyclicBarrier

来自WHY42
Riguz留言 | 贡献2021年5月4日 (二) 08:33的版本 (建立內容為「A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. <span class="article-label">CyclicBarriers</span> a…」的新頁面)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.


 class Solver {
   final int N;
   final float[][] data;
   final CyclicBarrier barrier;

   class Worker implements Runnable {
     int myRow;
     Worker(int row) { myRow = row; }
     public void run() {
       while (!done()) {
         processRow(myRow);

         try {
           barrier.await();
         } catch (InterruptedException ex) {
           return;
         } catch (BrokenBarrierException ex) {
           return;
         }
       }
     }
   }

   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();
   }
 }