当所有线程都执行到某行代码,才可已往下执行:
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); } } }
时间: 2024-10-12 09:25:01