java.util.concurrent.CyclicBarrier
一组线程共同等待,直到达到一个公共屏障点。
举个栗子,百米赛跑中,所有运动员都要等其他运动员都准备好后才能一起跑(假如没有发令员)。
1 import java.io.IOException; 2 import java.util.Random; 3 import java.util.concurrent.BrokenBarrierException; 4 import java.util.concurrent.CyclicBarrier; 5 import java.util.concurrent.ExecutorService; 6 import java.util.concurrent.Executors; 7 public class UseCyclicBarrier { 8 9 static class Runner implements Runnable { //远动员,每个运动员都是一个单独的线程 10 private CyclicBarrier barrier; //屏障点 11 private String name; 12 13 public Runner(CyclicBarrier barrier, String name) { 14 this.barrier = barrier; //每个运动员都要有这个屏障点信息(在这里就表现为:所有人都准备好) 15 this.name = name; 16 } 17 @Override 18 public void run() { 19 try { 20 Thread.sleep(1000 * (new Random()).nextInt(5)); //假设每个运动员都要准备一段时间 21 System.out.println(name + " 准备OK."); 22 barrier.await(); //准备好了就等待,等其他人都准备好了 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } catch (BrokenBarrierException e) { 26 e.printStackTrace(); 27 } 28 System.out.println(name + " Go!!"); //其他人都准备好了,跑! 29 } 30 } 31 32 public static void main(String[] args) throws IOException, InterruptedException { 33 CyclicBarrier barrier = new CyclicBarrier(3); // 3 34 ExecutorService executor = Executors.newFixedThreadPool(3); 35 36 executor.submit(new Thread(new Runner(barrier, "zhangsan"))); //zhangsan准备并等待 37 executor.submit(new Thread(new Runner(barrier, "lisi"))); //lisi准备并等待 38 executor.submit(new Thread(new Runner(barrier, "wangwu"))); //wangwu准备并等待 39 40 executor.shutdown(); 41 } 42 43 }
执行结果:
java.util.Concurrent.CountDownLatch
t1线程要等待t2和t3线程都准备好了才继续往下执行。
还是举个栗子,上面的那个栗子中,安排一个发令员,发令员走向场边,下面他应该打响发令枪,但是在这之前,他要确认其他人都准备好了,假设这里的跑步规则是发令员听到所有人都报完名字后才确认所有人都准备好了。
1 import java.util.concurrent.CountDownLatch; 2 3 public class UseCountDownLatch { 4 5 public static void main(String[] args) { 6 7 final CountDownLatch countDown = new CountDownLatch(2); 8 9 Thread t1 = new Thread(new Runnable() { 10 @Override 11 public void run() { 12 try { 13 System.out.println("进入线程t1" + "等待其他线程处理完成..."); 14 countDown.await();//计数,计数达到2后继续执行 15 System.out.println("t1线程继续执行..."); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 } 19 } 20 },"t1"); 21 22 Thread t2 = new Thread(new Runnable() { 23 @Override 24 public void run() { 25 try { 26 System.out.println("t2线程进行初始化操作..."); 27 Thread.sleep(3000); 28 System.out.println("t2线程初始化完毕,通知t1线程继续..."); 29 countDown.countDown();//报数 30 } catch (InterruptedException e) { 31 e.printStackTrace(); 32 } 33 } 34 }); 35 Thread t3 = new Thread(new Runnable() { 36 @Override 37 public void run() { 38 try { 39 System.out.println("t3线程进行初始化操作..."); 40 Thread.sleep(4000); 41 System.out.println("t3线程初始化完毕,通知t1线程继续..."); 42 countDown.countDown();//报数 43 } catch (InterruptedException e) { 44 e.printStackTrace(); 45 } 46 } 47 }); 48 49 t1.start(); 50 t2.start(); 51 t3.start(); 52 53 54 55 } 56 }
执行结果: