首页 > 代码库 > java路障CyclicBarrier
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); } } }
java路障CyclicBarrier
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。