zoukankan      html  css  js  c++  java
  • CyclicBarrier

     /**
    * CyclicBarrier 线程计数器
    *
    */
    1
    import java.util.concurrent.BrokenBarrierException; 2 import java.util.concurrent.CyclicBarrier; 3 4 public class CyclicBarrierTest { 5 private static final int THREAD_COUNT = 10; 6 7 public static CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); 8 9 public static void main(String[] args) { 10 for(int i = 0; i<THREAD_COUNT; i++){ 11 new Thread(new WorkThread(barrier)).start(); 12 } 13 } 14 15 } 16 17 class WorkThread implements Runnable{ 18 private CyclicBarrier barrier; 19 20 public WorkThread(CyclicBarrier barrier){ 21 this.barrier = barrier; 22 } 23 24 @Override 25 public void run() { 26 try { 27 System.out.println(Thread.currentThread().getName() + "working before await()"); 28 barrier.await();//线程在此等待,直到所有线程到达。。。才开始往下执行 29 System.out.println(Thread.currentThread().getName() + "working after await()"); 30 } catch (InterruptedException e) { 31 e.printStackTrace(); 32 } catch (BrokenBarrierException e) { 33 e.printStackTrace(); 34 } 35 } 36 }

    结果

    Thread-0working before await()
    Thread-1working before await()
    Thread-3working before await()
    Thread-2working before await()
    Thread-5working before await()
    Thread-4working before await()
    Thread-7working before await()
    Thread-9working before await()
    Thread-6working before await()
    Thread-8working before await()


    Thread-0working after await()
    Thread-8working after await()
    Thread-1working after await()
    Thread-3working after await()
    Thread-2working after await()
    Thread-5working after await()
    Thread-4working after await()
    Thread-9working after await()
    Thread-6working after await()
    Thread-7working after await()

     从上面的结果,可以知道:

     CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); 当调用barrier.await()方法时,当所有线程到达时,才会开始执行后面的代码。这个类很有用,平时自己做一些测试例子是比较常用的
  • 相关阅读:
    PPP协议 PAP认证
    交换机广播风暴,STP生成树协议,端口聚合
    传统远程注入线程,加载DLL
    EXE和DLL调用关系,DLL制作,钩子
    window bat批处理 实用脚本
    python利用scapy嗅探流量
    关于AWD线下攻防的经验
    APP 仿微信登录
    价值1500左右的毕业设计都开源啦
    EOS2.0环境搭建-centos7
  • 原文地址:https://www.cnblogs.com/chenmo-xpw/p/3938454.html
Copyright © 2011-2022 走看看