• 栅栏(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();
        }
    }
  • 相关阅读:
    [题解]北京2018
    [数据结构][字典树]Word Puzzles
    [数据结构][字典树]Hardwood Species
    [数学][广义欧拉定理]上帝与集合的正确用法
    Equal Sums
    Useful Decomposition
    网络流 EK算法
    线段树各类操作
    唯一分解定理
    Kuro and Walking Route
  • 原文地址:https://www.cnblogs.com/jpit/p/8444645.html
Copyright © 2020-2023  润新知