栅栏(CyclicBarrier)

package japan.example.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {

    public static void main(String[] args) throws Exception {

        CyclicBarrierTest test = new CyclicBarrierTest();
        test.test();
    }

    public void test() throws InterruptedException {
        int[][] data = new int[][] { //
                { 1, 2, 3, 4 }, //
                { 5, 6, 7, 8 }, //
                { 9, 10, 11, 12 }, //
                { 13, 14, 15, 16 } //
        };
        Solver solver = new Solver(data);
    }

}

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

    class Worker implements Runnable {
        int myRow;

        Worker(int row) {
            myRow = row;
        }

        public boolean done() {
            return false;
        }

        public void processRow(int myRow) {
            System.err.println("process " + myRow);
        }

        public void run() {
            while (!done()) {
                processRow(myRow);
                try {
                    barrier.await();
                } catch (InterruptedException ex) {
                    return;
                } catch (BrokenBarrierException ex) {
                    return;
                }
            }
        }
    }

    public Solver(int[][] matrix) throws InterruptedException {
        data = matrix;
        N = matrix.length;
        Runnable barrierAction = new Runnable() {
            @Override
            public void run() {

                System.err.println("run");
            }
        };
        barrier = new CyclicBarrier(N, barrierAction);

        List<Thread> threads = new ArrayList<>(N);
        for (int i = 0; i < N; i++) {
            Thread thread = new Thread(new Worker(i));
            threads.add(thread);
            thread.start();
        }

        // wait until done
        for (Thread thread : threads)
            thread.join();
    }
}
原文地址:https://www.cnblogs.com/jpit/p/8444645.html