浅析Java中CountDownLatch用法

CountDownLatch如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束。下面以一个模拟运动员比赛的例子加以说明。

  
  
1 import java.util.concurrent.CountDownLatch;
2   import java.util.concurrent.Executor;
3   import java.util.concurrent.ExecutorService;
4   import java.util.concurrent.Executors;
5
6   public class CountDownLatchDemo {
7 private static final int PLAYER_AMOUNT = 5 ;
8 public CountDownLatchDemo() {
9 // TODO Auto-generated constructor stub
10   }
11 /**
12 * @param args
13 */
14 public static void main(String[] args) {
15 // TODO Auto-generated method stub
16 // 对于每位运动员,CountDownLatch减1后即结束比赛
17 CountDownLatch begin = new CountDownLatch( 1 );
18 // 对于整个比赛,所有运动员结束后才算结束
19 CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
20 Player[] plays = new Player[PLAYER_AMOUNT];
21
22 for ( int i = 0 ;i < PLAYER_AMOUNT;i ++ )
23 plays[i] = new Player(i + 1 ,begin,end);
24
25 // 设置特定的线程池,大小为5
26 ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
27 for (Player p:plays)
28 exe.execute(p); // 分配线程
29 System.out.println( " Race begins! " );
30 begin.countDown();
31 try {
32 end.wait(); // 等待end状态变为0,即为比赛结束
33 } catch (InterruptedException e) {
34 // TODO: handle exception
35 e.printStackTrace();
36 } finally {
37 System.out.println( " Race ends! " );
38 }
39 exe.shutdown();
40 }
41 }

接下来是Player类

  
  
1 import java.util.concurrent.CountDownLatch;
2
3
4 public class Player implements Runnable {
5
6 private int id;
7 private CountDownLatch begin;
8 private CountDownLatch end;
9 public Player( int i, CountDownLatch begin, CountDownLatch end) {
10 // TODO Auto-generated constructor stub
11 super ();
12 this .id = i;
13 this .begin = begin;
14 this .end = end;
15 }
16
17 @Override
18 public void run() {
19 // TODO Auto-generated method stub
20 try {
21 begin.await(); // 等待begin的状态为0
22 Thread.sleep(( long )(Math.random() * 100 )); // 随机分配时间,即运动员完成时间
23 System.out.println( " Play " + id + " arrived. " );
24 } catch (InterruptedException e) {
25 // TODO: handle exception
26 e.printStackTrace();
27 } finally {
28 end.countDown(); // 使end状态减1,最终减至0
29 }
30 }
31 }
转自http://en.wikipedia.org/wiki/Double-checked_locking
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CountDownLatch 是一个同步工具类,在多线程环境常常用于控制线程的执行顺序或者等待某个事件的发生。它的主要作用是让一组线程等待某个事件的发生,当事件发生后,所有等待的线程都可以继续执行。 CountDownLatch 的使用步骤如下: 1. 创建一个 CountDownLatch 对象,指定需要等待的线程数。 2. 在需要等待的线程,调用 CountDownLatch 的 await() 方法,等待事件的发生。 3. 当事件发生时,调用 CountDownLatch 的 countDown() 方法,通知等待的线程可以继续执行。 下面是一个简单的例子: ``` import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); Thread t1 = new Thread(new Task("Task1", latch)); Thread t2 = new Thread(new Task("Task2", latch)); Thread t3 = new Thread(new Task("Task3", latch)); t1.start(); t2.start(); t3.start(); latch.await(); // 等待所有任务执行完成 System.out.println("All tasks have been completed."); } static class Task implements Runnable { private String name; private CountDownLatch latch; public Task(String name, CountDownLatch latch) { this.name = name; this.latch = latch; } @Override public void run() { System.out.println(name + " is running..."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + " has completed."); latch.countDown(); } } } ``` 在这个例子,我们创建了一个 CountDownLatch 对象,并指定需要等待的线程数为 3。然后创建了 3 个线程,并让它们执行一个简单的任务:输出线程名字、等待 1 秒钟,然后输出线程名字并调用 countDown() 方法。最后在主线程调用 await() 方法等待所有任务执行完成。当所有任务执行完成后,输出一条“所有任务已完成”的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值