demo1:
package concurrent._Barrier; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class Demo { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(5); for(int i = 0 ;i < 5 ; i ++){ new Woker(new Integer(i).toString(),cyclicBarrier).start(); } } } class Woker extends Thread{ private CyclicBarrier cyclicBarrier; public Woker(String name,CyclicBarrier cyclicBarrier){ super(name); this.cyclicBarrier = cyclicBarrier; } @Override public void run() { String threadName = this.getName(); try { int i = new Random().nextInt(5000); Thread.sleep(i); System.out.println(threadName + "已经在运行" + i + "ms后到达栅栏"); cyclicBarrier.await(); System.out.println(threadName + "继续运行"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }
结果:
4已经在运行71ms后到达栅栏
1已经在运行1925ms后到达栅栏
0已经在运行2006ms后到达栅栏
2已经在运行3056ms后到达栅栏
3已经在运行4434ms后到达栅栏
3继续运行
4继续运行
1继续运行
2继续运行
0继续运行
修改代码:
在到达栅栏之后,栅栏随机选取一个线程,进行一个操作。
package concurrent._Barrier; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class Demo { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在执行Runnable"); } }); for(int i = 0 ;i < 5 ; i ++){ new Woker(new Integer(i).toString(),cyclicBarrier).start(); } } } class Woker extends Thread{ private CyclicBarrier cyclicBarrier; public Woker(String name,CyclicBarrier cyclicBarrier){ super(name); this.cyclicBarrier = cyclicBarrier; } @Override public void run() { String threadName = this.getName(); try { int i = new Random().nextInt(5000); Thread.sleep(i); System.out.println(threadName + "已经在运行" + i + "ms后到达栅栏"); cyclicBarrier.await(); Thread.sleep(1000); System.out.println(threadName + "继续运行"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }
结果:
4已经在运行1582ms后到达栅栏
0已经在运行1932ms后到达栅栏
1已经在运行1967ms后到达栅栏
2已经在运行2128ms后到达栅栏
3已经在运行3582ms后到达栅栏
3正在执行Runnable
4继续运行
2继续运行
0继续运行
1继续运行
3继续运行
从结果可以看出,在到达栅栏之后,首先执行Runnable中的函数,然后再执行线程中的剩余的操作。