zoukankan      html  css  js  c++  java
  • java路障CyclicBarrier

    当所有线程都执行到某行代码,才可已往下执行:

    package threadLock;
    
    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) {
            ExecutorService service = Executors.newCachedThreadPool();
            final CyclicBarrier barrier = new CyclicBarrier(3);
            for(int i = 0; i < 3; ++i){
                Runnable runnable  = new Runnable() {
                    
                    @Override
                    public void run() {
                        
                            try {
                                Thread.sleep(new Random().nextInt(1000));
                                System.out.println("线程 " + Thread.currentThread().getName() + "即将到达目的地 1,当前已有" + (barrier.getNumberWaiting() + 1) + "个到达," + (barrier.getNumberWaiting() == 2 ? "继续走啊" : "") );
                                barrier.await();
                                Thread.sleep(new Random().nextInt(1000));
                                System.out.println("线程 " + Thread.currentThread().getName() + "即将到达目的地 2,当前已有" + (barrier.getNumberWaiting() + 1) + "个到达," + (barrier.getNumberWaiting() == 2 ? "继续走啊" : "") );
                                barrier.await();
                                Thread.sleep(new Random().nextInt(1000));
                                System.out.println("线程 " + Thread.currentThread().getName() + "即将到达目的地 3,当前已有" + (barrier.getNumberWaiting() + 1) + "个到达," + (barrier.getNumberWaiting() == 2 ? "继续走啊" : "") );
                                barrier.await();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (BrokenBarrierException e) {
                                e.printStackTrace();
                            }
                        }
                        
                    
                };
                service.execute(runnable);
            }
        }
    }
  • 相关阅读:
    FIREDAC操作SQLITE内存数据库
    DELPHI移动端支付宝支付
    DELPHI支付宝支付代码
    DELPHI微信支付代码
    mssql内存表
    Ubuntu下添加开机启动项的2种方法
    docker容器中安装vim
    使用find命令查找Linux中的隐藏文件的方法
    Go语言_RPC_Go语言的RPC
    Mac下export生效
  • 原文地址:https://www.cnblogs.com/zhouquan-1992-04-06/p/6286256.html
Copyright © 2011-2022 走看看