CyclicBarrier分析与实例
一,介绍
CyclicBarrier是一个保持多个线程共享同一个状态的工具类。
也就是说在多线程环境下,能够通过设定某一个状态来达到线程之间的同步。这个类有两个有參构造方法。各自是CyclicBarrier(int n)和CyclicBarrier(int n, Runnable r)。第一个构造方法的意思是指给这个类设置等待点到多少时才运行在run方法中调用await方法之后的操作;第二个构造器的Runnable能够看作一个等待点的狼烟,狼烟是什么,是一种信号。也就是说,在等待线程达到n这个数量之后,会開始运行run方法中调用await方法之后的代码,而在调用这些代码前,会先放狼烟,然后再运行那些代码。
这个类在多线程统计数据时还是非常实用的。可是要注意,假设你的线程数量总是达不到设置的n的数量,那么这时,操作将被堵塞,即await方法后面的代码总是不能运行。
二,样例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | package test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrrierTest { static int count = 0 ; static List<Integer> data= Collections.synchronizedList( new ArrayList<Integer>()); public static void main(String[] args) { //设置2个等待线程,存在两个等待线程时,计算集合中的何,然后再清除集合中的数据 CyclicBarrier cb = new CyclicBarrier( 2 , new Runnable() { public void run() { int sum = 0 ; for ( int i = 0 ; i < data.size(); i++) { sum += data.get(i); } System.out.println( "current sum is " + sum); data.clear(); } }); int n = 10 ; for ( int i = 0 ; i< n; i++) { new Thread( new CBThread( 2 , cb,data)).start(); //开启n个线程 } } } class CBThread implements Runnable{ private int n; private CyclicBarrier cb; private List<Integer> data; public CBThread( int n,CyclicBarrier cb,List<Integer> data) { this .n = n; this .cb = cb; this .data = data; } public void run() { Random random = new Random(); // while(!done()) { int n = random.nextInt( 10 ); data.add(n); System.out.println(Thread.currentThread().getName() + " ======" + n + ", " + cb.getNumberWaiting()); try { cb.await(); //await方法后面的代码总是在cb.getNumberWait等于n的时候才运行 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println( "走起......" + CyclicBarrrierTest.count); // } } private boolean done() { return false ; } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步