CyclicBarrier 使用方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qfzhangwei/article/details/79434763
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by xiayin on 2018/3/4.
 */
public class Cyclic {
    final int N;
    final float[][] data;
    final CyclicBarrier barrier;
    private volatile boolean done;

    class Worker implements Runnable {
        int myRow;

        Worker(int row) {
            myRow = row;
        }

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

    public Cyclic(float[][] matrix) throws InterruptedException {
        data = matrix;
        N = matrix.length;
        Runnable barrierAction =
                new Runnable() {
                    public void run() {
                        System.out.println("恭喜运行结束了");
                        done = true;
                    }
                };
        barrier = new CyclicBarrier(N, barrierAction);

        List<Thread> threads = new ArrayList<Thread>(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();
    }

    public static void main(String[] args) throws InterruptedException {
        new Cyclic(new float[][]{{1.0f,2.0f},{3.0f,4.0f}});
    }
}
CyclicBarrier 多个线程运行完毕后,执行最后一步(常用的数学运算,并发执行,结果汇总);

猜你喜欢

转载自blog.csdn.net/qfzhangwei/article/details/79434763
今日推荐