java并发编程实战栅栏

栅栏类似于闭锁,它能阻塞一组线程直到某个事件发生。栅栏与闭锁的关键区别在于,所有线程必须同时到达栅栏位置,才能继续执行。闭锁用于等待事件,而栅栏用于等待其他线程,且能够重复执行。
 import java.util.concurrent.BrokenBarrierException;
 import java.util.concurrent.CyclicBarrier;
 
 public class TestCyclicBarrier {
    private final CyclicBarrier barrier;
private final Worker[] workers;

public TestCyclicBarrier() {
    int count = Runtime.getRuntime().availableProcessors();
    barrier = new CyclicBarrier(count, new Runnable() {
        @Override
        public void run() {
            System.out.println("所有线程均到达栅栏位置,开始下一轮");
        }
    });
    this.workers = new Worker[count];
    for(int i = 0; i < count; i++) {
        workers[i] = new Worker(i);
    }
}

private class Worker implements Runnable {
    int i;
    
    public Worker(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        for(int index = 1; index < 3; index++) {
            System.out.println("线程" + i + "第" + index + "次到达栅栏位置,等待其他线程!");
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
    
}

public void start() {
    for(int i = 0; i < workers.length; i++) {
        new Thread(workers[i]).start();
    }
}

public static void main(String[] args) {
    new TestCyclicBarrier().start();
}
}

//创建栅栏, 等待线程
package com.demo;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
/**
 * 创建线程数量
 */
private static final int SIZE = 5; 

public static void main(String[] args) {
    //创建关卡对象
    CyclicBarrier cb = new CyclicBarrier(SIZE, new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ":" + " all sub thead end");//所有子线程执行完毕时执行
        }});
    //创建并启动五个子线程
    for(int i = 0; i < SIZE; i++) {
        new Thread(new SubThread(cb)).start();
    }
}

static class SubThread implements Runnable{

    private CyclicBarrier cb; //栅栏对象

    public SubThread(CyclicBarrier cb) {
        this.cb = cb;
    }

    @Override
    public void run() {
        //当前线程开始运行
        System.out.println(Thread.currentThread().getName() + ": sub thread starting running");
        try {
            cb.await();//计数器加1,等待其他线程执行到同样的地方
            //子线程全部继续执行
            System.out.println(Thread.currentThread().getName() + ":" +" all sub thread start doing other things");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}

你可能感兴趣的:(java并发编程实战栅栏)