package test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /**** * 需要线程数为N * 第1个线程执行前直接等待 await * 第2个线程执行前直接等待 await * 第3个线程执行前直接等待 await * 第n个线程执行前直接等待 await * 最后:大家一起去执行目标方法 */ public class CyclicBarrierTest { CyclicBarrier cyclicBarrier = new CyclicBarrier(10); AtomicInteger num = new AtomicInteger(0); int value = 1; public void test(){ System.out.println("hello"+ Thread.currentThread().getName()); value++; num.getAndIncrement(); } public void count(){ System.out.println("value="+value++); System.out.println("num="+num.getAndIncrement()); } public static void main(String[] args) throws Exception{ final CyclicBarrierTest test = new CyclicBarrierTest(); List<Thread> list = new ArrayList<Thread>(); for (int i = 0; i <100 ; i++) { Thread thread1 = new Thread(new Runnable() { public void run() { System.out.println(Thread.currentThread().getName()+"进入等待"); try { test.cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"即将执行目标代码"); test.test(); } }); list.add(thread1); } Thread.sleep(1000); for (Thread thread : list) { Thread.sleep(100); thread.start(); } Thread.sleep(1000); test.count(); } }
java CyclicBarrier
最新推荐文章于 2024-01-30 14:21:56 发布