Java之CyclicBarrier使用

1:CyclicBarrier类说明

一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时 CyclicBarrier 很有用。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier

2:使用场景

需要所有的子任务都完成时,才执行主任务,这个时候就可以选择使用CyclicBarrier

3:查看api



现在写一个demo玩下,

package cn.kge.com.thread;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {
	public static void main(String[] args) throws IOException, InterruptedException {  
        //如果将参数改为4,但是下面只加入了3个选手,这永远等待下去  
        //Waits until all parties have invoked await on this barrier.   
        CyclicBarrier barrier = new CyclicBarrier(4);  
  
        ExecutorService executor = Executors.newFixedThreadPool(4);  
        executor.submit(new Thread(new Runner(barrier, "张三")));  
        executor.submit(new Thread(new Runner(barrier, "李四")));  
        executor.submit(new Thread(new Runner(barrier, "王五")));  
        executor.submit(new Thread(new Runner(barrier, "老刘")));  
        
        executor.shutdown();  
    }  
}  
  
class Runner implements Runnable {  
    // 一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)  
    private CyclicBarrier barrier;  
  
    private String name;  
  
    public Runner(CyclicBarrier barrier, String name) {  
        super();  
        this.barrier = barrier;  
        this.name = name;  
    }  
  
    @Override  
    public void run() {  
        try {  
            Thread.sleep(1000 * (new Random()).nextInt(8));  
            System.out.println(name + " 马上到...");  
            // barrier的await方法,在所有参与者都已经在此 barrier 上调用 await 方法之前,将一直等待。  
            barrier.await();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } catch (BrokenBarrierException e) {  
            e.printStackTrace();  
        }  
        System.out.println("一起泡妞去");  
    }  
}


你可能感兴趣的:(java,多线程,android)